提问人:CYBER HK 提问时间:8/20/2022 更新时间:8/20/2022 访问量:49
代表变量创建嵌套循环 [closed]
Create nested loops on behalf of a varaible [closed]
问:
我有一个长度为 n = 3 的嵌套列表
a = [[1, 2], [3, 4], [5, 6]]
我想要这个结果
[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
我通过以下方式得到结果:
ans = []
for i in a[0]:
for j in a[1]:
for k in a[2]:
ans.append((i, j, k))
print(ans)
但是如果我更改 a 的长度,我必须删除或添加嵌套循环:
ans = []
for i in a[0]:
---
---
ans.append((i, ___))
一个简单的解决方案是:
from itertools import product
print(list(product(*a)))
但我想手动实现它
答:
1赞
The Thonnu
8/20/2022
#1
您可以尝试这样的递归函数:
def product(lst):
for item in lst[0]:
if len(lst) > 1:
for result in product(lst[1:]):
yield [item] + result
else:
yield [item]
a = [[1, 2], [3, 4], [5, 6]]
print(list(product(a)))
输出:
[[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]]
注意:如果你想要元组,只需使用:
print([tuple(x) for x in product(a)])
输出:
[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
上一个:嵌套列表上的递归
评论
itertools.product