如果我有这些清单:
a = [1,2,3]
b = [4,5,6]
如何在列表b中添加列表中的每个元素?
final_list = [5,6,7,6,7,8,7,8,9]
我尝试使用2 for循环,但作为一个业余爱好者,我想有一个更有效的方法。干杯!
答案 0 :(得分:4)
简单地
a = [1,2,3]
b = [4,5,6]
# Multiplication
final_list = [x*y for x in a for y in b]
[4,5,6,8,10,12,12,15,18]
# Addition
final_list = [x+y for x in a for y in b]
[5,6,7,6,7,8,7,8,9]
答案 1 :(得分:4)
你也可以像以前的答案一样做补充,
>>> [i+j for i in a for j in b]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
答案 2 :(得分:3)
您可以使用itertools.product
计算a
和b
的笛卡尔积,然后计算每对的乘积/总和:
>>> import itertools
>>> a = [1,2,3];b = [4,5,6]
>>> list(itertools.product(a,b)) # This step isn't needed. It's just to show the result of itertools.product
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
>>> [i + j for i, j in itertools.product(a, b)]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
>>> [i * j for i, j in itertools.product(a, b)]
[4, 5, 6, 8, 10, 12, 12, 15, 18]
答案 3 :(得分:0)
如何处理n个列表?
from itertools import product
def listSum(lists):
return [sum(list) for list in product(*lists)]
print(listSum(([1,2,3],[4,5,6]))) #=> [5, 6, 7, 6, 7, 8, 7, 8, 9]
print(listSum(([1,2,3], ))) #=> [1, 2, 3]
print(listSum(([1,2,3],[4,5,6],[7,8,9]))) #=> [12, 13, 14, 13, 14, 15, 14, 15, 16, 13, 14, 15, 14, 15, 16, 15, 16, 17, 14, 15, 16, 15, 16, 17, 16, 17, 18]