gpt4 book ai didi

python - 如何迭代不同列表的产品?

转载 作者:太空宇宙 更新时间:2023-11-04 00:45:35 24 4
gpt4 key购买 nike

我有以下问题:

我有一个列表 l1,我想用函数 itertools.product 迭代产品,我还想包含第二个列表 l2以同样的方式。

例如:

l1 = [1, 2, 3, 4]
l2 = ['a', 'b', 'c', 'd']
for i in list(itertools.product(l1, repeat = 2)):
print(i)

输出是:

(1, 1)
(1, 2)
...

我觉得这个很清楚了。但是我怎样才能设法包含第二个列表并获得这样的输出:

(1, a),(1, a)
(1, a),(2, b)
(1, a),(3, c)
(1, a),(4, d)

(2, b),(1, a)
(2, b),(2, b)
(2, b),(3, c)
(2, b),(4, d)

(3, c),(1, a)
(3, c),(2, b)
(3, c),(3, c)
(3, c),(4, d)

(4, d),(1, a)
(4, d),(2, b)
(4, d),(3, c)
(4, d),(4, d)

我知道一个合适的解决方案是组合 for 循环。但这不适合我,因为我想增加 repeat 计数器。

最佳答案

通过向 product 提供列表的 zip:

for i in product(zip(l1,l2), repeat = 2):
print(i)

不需要在 list 中包装,for 循环负责为您调用迭代器上的 next

如果您想要每 4 个组合换行,请使用 enumerate(从 1 开始)并在 c % 40:

for c, i in enumerate(product(zip(l1,l2), repeat = 2), 1):
print(i, '\n' if c % 4 == 0 else '')

输出:

((1, 'a'), (1, 'a')) 
((1, 'a'), (2, 'b'))
((1, 'a'), (3, 'c'))
((1, 'a'), (4, 'd'))

((2, 'b'), (1, 'a'))
((2, 'b'), (2, 'b'))
((2, 'b'), (3, 'c'))
((2, 'b'), (4, 'd'))

((3, 'c'), (1, 'a'))
((3, 'c'), (2, 'b'))
((3, 'c'), (3, 'c'))
((3, 'c'), (4, 'd'))

((4, 'd'), (1, 'a'))
((4, 'd'), (2, 'b'))
((4, 'd'), (3, 'c'))
((4, 'd'), (4, 'd'))

关于python - 如何迭代不同列表的产品?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39804860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com