+ 3
better idea? handling lists
i have 2 lists, with same length: a=[1,2,3] , b=[5,7,9] and i want output like this: c=[1+5, 2+7, 3+9], equal to [6,9,12] my best method is: c=[a[i]+b[i] for i in range(len(a))] but there should be better answer thanks for your attention
6 Antworten
+ 9
c = [x+y for x, y in zip(a, b)]
+ 6
#Also this works:
c = list(map(lambda x, y: x + y, a, b))
+ 3
And if you have lists of lists ,you can add them like this
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
print(sum(x) for x in zip(*lists_of_lists)
#prints [5,7,9]
+ 1
there's a better solution:
import numpy as np
numpy arrays are vastly superior in terms of performance and handling when it comes to arithmetic operations.
https://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html
0
This works perfectly and is simpler than zip
c = list(map(lambda x, y: x + y, a, b))