我有这段代码:
list_1 = [11, 22]
list_2 = [33, 44, 55 ,66]
list_3 = [77, 88 ,99]
我想对列表中的每个元素求和。即11 + 33 + 77,11 + 33 + 88,... 22 + 33 + 77,22 + 33 + 88 ......并将所有款项列入最终名单
我有以下几行:
list_1 = [11, 22]
list_2 = [33, 44, 55 ,66]
list_3 = [77, 88 ,99]
result = []
for L_1 in list_1:
for L_2 in list_2:
for L_3 in list_3:
result.append(L_1 + L_2 + L_3)
print result # to output all elements
print list(set(result)) # to not showing duplicates
这些代码运作良好,但看起来很笨拙。如果有20个或更多的列表参与计算,那么它看起来并不好。
你能告诉我一个更好的方法吗?答案 0 :(得分:3)
这种组合称为笛卡尔积。您可以使用itertools.product
获取它。
from itertools import product
list_1 = [11, 22]
list_2 = [33, 44, 55, 66]
list_3 = [77, 88, 99]
result = {sum(t) for t in product(list_1, list_2, list_3)}
print(sorted(result))
<强>输出强>
[121, 132, 143, 154, 165, 176, 187]
如果您事先不知道有多少个名单,您甚至可以使用product
:
all_lists = list_1, list_2, list_3
result = {sum(t) for t in product(*all_lists)}
product
迭代器会从您传递它的迭代中产生项目的元组。然后,我们将这些元组传递给内置sum
函数以执行添加。
这里&#34; raw&#34; product
的输出如下:
from itertools import product
list_1 = [1, 2]
list_2 = [3, 4]
list_3 = [5, 6]
all_lists = list_1, list_2, list_3
for t in product(*all_lists):
print(t)
<强>输出强>
(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)
答案 1 :(得分:1)
map(sum, product(*lists))
演示:
>>> from itertools import product
>>> lists = [11, 22], [33, 44, 55, 66], [77, 88, 99]
>>> map(sum, product(*lists))
[121, 132, 143, 132, 143, 154, 143, 154, 165, 154, 165, 176, 132, 143, 154, 143, 154, 165, 154, 165, 176, 165, 176, 187]