我得到了两个列表:
list_1 = [a1, a2, a3, ... a36]
list_2 = [b1, b2, b3,... b12]
根据这样的算法,我怎么能得到这两个列表的总和
a1 + b1, a1+b2, a1+b3,... , a1+b12
then
a2+b1, a2+b2, a2+b3,..., a2+b12
使用itertools.product
例如:
from itertools import product
list_1 = [1,2,3]
list_2 = [4,5,6]
print([sum(i) for i in product(list_1, list_2)])
输出:
[5, 6, 7, 6, 7, 8, 7, 8, 9]
这个简单的代码也可以工作:
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7]
list_3 = [a+b for a in list_1 for b in list_2] # Adding them up pairwise
现在,list_3
将包含所有的和。
从你的问题来看,你似乎想要这个:
list_1 = [1,2,3]
list_2 = [4,5,6]
list_2_sum = sum(list_2)
[i + list_2_sum for i in list_1]
#[16, 17, 18]
或者如果您的list_1
较长:
list_1 = [1, 2, 3, 4]
list_2 = [4, 5, 6]
list_2_sum = sum(list_2)
[x + list_2_sum for x, _ in zip(list_1, list_2)]
#[16, 17, 18]