kk是存在的列表数。 l1,l2,l3是列表。在下面的代码中,我使用了3个for循环将元素添加到3个列表中。变量k的值可能会有所不同,因此列表。我想知道如何使用递归来实现这一目标。
kk = 3
l1 = [8,5,4]
l2 = [3,11,9]
l3 = [5,9,15,8]
maxi = []
for i in l1:
for j in l2:
for k in l3:
maxi.append(i+j+k)
答案 0 :(得分:2)
听起来像您在寻找
[sum(t) for t in itertools.product(l1, l2, l3)]
这将导致
[16, 20, 26, 19, 24, 28, 34, 27, 22, 26, 32, 25, 13, 17, 23, 16, 21, 25, 31, 24, 19, 23, 29,
22, 12, 16, 22, 15, 20, 24, 30, 23, 18, 22, 28, 21]
此处itertools.product
生成输入可迭代项的Cartesian product。如果列表中有未知数量的可迭代对象,则可以
iterables = [l1, l2, l3, ...]
[sum(t) for t in itertools.product(*iterables)]
将其解压缩为参数
递归解决方案看起来像这样。警告:与itertools
解决方案相比,它在各个方面都会变得更糟。
def summations(*iterables, sums=()):
if not iterables:
return list(sums)
head, *tail = iterables
if not sums:
return summations(*tail, sums=head)
sums = (x+y for y in sums for x in head)
return summations(*tail, sums=sums)
summations(l1, l2, 3)
# [16, 20, 26, 19, 24, 28, 34, 27, 22, 26, 32, 25, 13, 17, 23, 16, 21, 25, 31, 24, 19, 23, 29,
# 22, 12, 16, 22, 15, 20, 24, 30, 23, 18, 22, 28, 21]