python中的单个列表添加
如果我有这些清单:python中的单个列表添加,python,list,Python,List,如果我有这些清单: a = [1,2,3] b = [4,5,6] 如何通过列表b中的all添加列表a中的每个元素 final_list = [5,6,7,6,7,8,7,8,9] 我尝试过使用2 for循环,但作为一个业余爱好者,我认为有一种更有效的方法。干杯 您可以使用计算a和b的笛卡尔积,然后计算每对的积/和: >>> import itertools >>> a = [1,2,3];b = [4,5,6] >>> list(ite
a = [1,2,3]
b = [4,5,6]
如何通过列表b中的all添加列表a中的每个元素
final_list = [5,6,7,6,7,8,7,8,9]
我尝试过使用2 for循环,但作为一个业余爱好者,我认为有一种更有效的方法。干杯 您可以使用计算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]
简单地
[4,5,6,8,10,12,12,15,18]
[5,6,7,6,7,8,7,8,9]
你也可以像前面的答案一样做加法
>>> [i+j for i in a for j in b]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
处理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]
请展示你的努力,我没有想到。为什么不使用
sum
而不是reduce(lambda x,y:x+y,list,0)
?在最初的问题中,他要求的是乘积而不是总和。。。。因此,在编辑时,我使用了相同的逻辑,但可以简化
>>> [i+j for i in a for j in b]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
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]