【发布时间】: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 无法正常工作,因为我在两个循环中使用了相同的对象。但是,我希望 Test2 和 Test3 产生相同的结果,因为唯一的区别是我将迭代器对象首先转换为 Test3 中的列表。
我非常感谢有关此问题的任何解释。我在 Ubuntu 20.04 中使用 Python 3.8.2。
【问题讨论】:
标签: python loops iterator combinations