我现在有:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
我希望有:
[1, 2, 3]
+ + +
[4, 5, 6]
|| || ||
[5, 7, 9]
仅仅是两个列表的元素相加。
我当然可以迭代这两个列表,但我不想这样做。
最python化的方式是什么?
我现在有:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
我希望有:
[1, 2, 3]
+ + +
[4, 5, 6]
|| || ||
[5, 7, 9]
仅仅是两个列表的元素相加。
我当然可以迭代这两个列表,但我不想这样做。
最python化的方式是什么?
当前回答
我还没有计时,但我怀疑这将是相当快的:
import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]
list_sum = (np.add(list1, list2)).tolist()
[5, 7, 9]
其他回答
使用map和operator.add:
>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]
或者压缩一个列表理解:
>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]
时间比较:
>>> list2 = [4, 5, 6]*10**5
>>> list1 = [1, 2, 3]*10**5
>>> %timeit from operator import add;map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop
>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop
>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop
>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop
>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop
也许“最python化的方式”应该包括处理list1和list2大小不同的情况。运用其中的一些方法,你会不动声色地得到答案。numpy方法会让您知道,很可能使用ValueError。
例子:
import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)
如果这是你问题中的函数你想要什么结果?
a_list = []
b_list = []
for i in range(1,100):
a_list.append(random.randint(1,100))
for i in range(1,100):
a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]
在我看来,使用numpy更简单:
import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)
结果:
有关详细参数信息,请查看这里:numpy.add
[a + b for a, b in zip(list1, list2)]