我现在有:
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化的方式是什么?
当前回答
正如其他人所描述的那样,一个快速且节省空间的解决方案是使用numpy (np)及其内置的矢量操作功能:
1. 与Numpy
x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y
2. 与整体功能
2.1λ
list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)
注意map()支持多个参数。
2.2 zip和列表理解
list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]
其他回答
使用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
这将适用于2个或更多的列表;遍历列表的列表,但使用numpy加法处理每个列表的元素
import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]
lists = [list1, list2]
list_sum = np.zeros(len(list1))
for i in lists:
list_sum += i
list_sum = list_sum.tolist()
[5.0, 7.0, 9.0]
[list1[i] + list2[i] for i in range(len(list1))]
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 )]
[a + b for a, b in zip(list1, list2)]