【问题标题】:How do I iterate over the product of different lists?如何迭代不同列表的产品?
【发布时间】:2017-02-09 19:39:54
【问题描述】:

我有以下问题:

我有一个列表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-counter。

【问题讨论】:

    标签: python list python-3.x for-loop itertools


    【解决方案1】:

    通过将列表中的zip 提供给product

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

    不需要包裹在 list 中,for 循环会为您在迭代器上调用 next

    如果您希望每 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 '')
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2015-02-04
      • 2022-01-23
      • 2021-04-27
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2016-08-28
      • 2016-05-14
      • 2018-02-02
      相关资源
      最近更新 更多