List calculation in python

Suppose I have two lists of different lengths.

a = [8,9,4,7,5,6,1,4,8]
b = [6,4,7,1,5,8,3,6,4,4]

I need a list:

c= a-b

#output = [2, 5, -3, 6, 0, -2, -2, -2, 4]

How can i achieve this?

I tried operator.subwith the display function. But I get an error due to the different length of the list.

c = map(operator.sub, a, b)

TypeError: unsupported operand type for -: 'NoneType' and 'int'

+4
source share
2 answers
from itertools import starmap
from operator import sub

a = [8,9,4,7,5,6,1,4,8]
b = [6,4,7,1,5,8,3,6,4,4]

output = list(starmap(sub, zip(a, b)))

If you do not want to use list comprehension, this can be done with itertools.starmap.

You can also use a map, although I think starmap is the best option. Using a map, you can use nested zipto shorten a longer argument.

output = map(sub, *zip(*zip(a, b)))
print(list(output))
# [2, 5, -3, 6, 0, -2, -2, -2, 4]
+4
source

zip :

>>> a = [8,9,4,7,5,6,1,4,8]
>>> b = [6,4,7,1,5,8,3,6,4,4]

>>> [x - y for x, y in zip(a, b)]
[2, 5, -3, 6, 0, -2, -2, -2, 4]
+7

Source: https://habr.com/ru/post/1672441/


All Articles