【问题标题】:Nested loop over combination嵌套循环组合
【发布时间】:2020-07-17 00:25:11
【问题描述】:

对组合进行迭代不会给出预期的迭代次数。为了说明我的问题:

import itertools

combinations = itertools.combinations(range(10), 1) # The combination has 10 elements

# Test1
count = 0
for c1 in combinations:
    for c2 in combinations:
        count += 1
print("Test1:", count)

# Test2
combinations1 = itertools.combinations(range(10), 1)
combinations2 = itertools.combinations(range(10), 1)

count = 0
for c1 in combinations1:
    for c2 in combinations2:
        count += 1
print("Test2:", count)

# Test3
combinations1 = list(itertools.combinations(range(10), 1))
combinations2 = list(itertools.combinations(range(10), 1))

count = 0
for c1 in combinations1:
    for c2 in combinations2:
        count += 1
print("Test3:", count)

我正在迭代 10 个元素的组合。使用双嵌套循环,我预计 100 次迭代 (10x10)。但是,我得到以下结果:

Test1: 9
Test2: 10
Test3: 100

我可以理解Test1 无法正常工作,因为我在两个循环中使用了相同的对象。但是,我希望 Test2Test3 产生相同的结果,因为唯一的区别是我将迭代器对象首先转换为 Test3 中的列表。

我非常感谢有关此问题的任何解释。我在 Ubuntu 20.04 中使用 Python 3.8.2。

【问题讨论】:

    标签: python loops iterator combinations


    【解决方案1】:

    在第二种情况下,您只能迭代combinations2 一次。这可以通过添加一些prints 来证明:

    count = 0
    for c1 in combinations1:
        print("Outer")
        for c2 in combinations2:
            print("inner")
            count += 1
    print("Test2:", count)
    
    Outer
    inner
    inner
    inner
    inner
    inner
    inner
    inner
    inner
    inner
    inner
    Outer
    Outer  <-- Noteworthy
    Outer
    Outer
    Outer
    Outer
    Outer
    Outer
    Outer
    Test2: 10
    

    combinations 返回一个迭代器,一个迭代器只能迭代一次。如果你在它耗尽后尝试调用next,它仍然会被耗尽。

    您的第三个示例有效,因为它是正在迭代的列表。当你迭代一个列表时,iter(a_list) 被隐式调用,每次都会创建一个新的迭代器。将其与评估自身的iter(an_iterator) 进行对比;不是新的迭代器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 2022-05-12
      • 2021-12-02
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多