我现在有:
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化的方式是什么?
当前回答
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 )]
其他回答
如果您需要处理不同大小的列表,不用担心!很棒的itertools模块已经介绍过了:
>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>
在Python 2中,zip_longest被称为izip_longest。
参见相关回答,并对另一个问题进行评论。
使用map与lambda函数:
>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]
正如其他人所描述的那样,一个快速且节省空间的解决方案是使用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)]
也许“最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)
如果这是你问题中的函数你想要什么结果?
在我看来,使用numpy更简单:
import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)
结果:
有关详细参数信息,请查看这里:numpy.add