简体   繁体   English

如何遍历不同列表的产品?

[英]How do I iterate over the product of different lists?

I have the following problem: 我有以下问题:

I have a list l1 and I want to iterate over the product with the function itertools.product , I also want to include the second list l2 in the same way. 我有一个列表l1 ,我想使用功能itertools.product遍历该产品,我也想以同样的方式包括第二个列表l2

For example: 例如:

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

The output is: 输出为:

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

I think this is very clear. 我认为这很清楚。 But how can I manage to include the second list and get an output like this: 但是我如何设法包括第二个列表并获得如下输出:

(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)

I know that a proper solution would be to combine for-loops. 我知道适当的解决方案是合并for循环。 But that doesn't fit for me as I want to increase the repeat -counter. 但这不适合我,因为我想增加repeat计数器。

By providing a zip of the lists to product : 通过提供product列表的zip

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

Wrapping in a list isn't required, the for loop takes care of calling next on the iterator for you. 不需要包装在list中,for循环会为您处理在迭代器上的next调用。

If you want a new-line for every 4 combinations, use enumerate (starting from 1 ) and add a \\n when c % 4 is 0 : 如果要每4个组合换行,请使用enumerate (从1开始)并在c % 40时添加\\n

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

Output: 输出:

((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')) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM