简体   繁体   English

为什么在传递非空可迭代对象时枚举为空?

[英]Why is enumerate empty when passed a non-empty iterable?

It's my understanding that the enumerate() function will loop over each item in an iterable.据我了解, enumerate() function 将遍历迭代中的每个项目。 However, in the example below is does not loop at all when given a non-empty iterable.但是,在下面的示例中,当给定一个非空的可迭代对象时,它根本不会循环。

import itertools
x = itertools.chain(
    itertools.combinations([1, 2, 3], 1),
    itertools.combinations([1, 2, 3], 2),
    itertools.combinations([1, 2, 3], 3),
)
print(list(x))
print(list(enumerate(x)))
print(list(enumerate(list(x))))
print(list(enumerate([(1, ), (2, ), (3, ), (1, 2), (1, 3), (2, 3), (1, 2, 3)])))

Output: Output:

[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
[]
[]
[(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 2)), (4, (1, 3)), (5, (2, 3)), (6, (1, 2, 3))]

Expected output:预期 output:

[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
[(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 2)), (4, (1, 3)), (5, (2, 3)), (6, (1, 2, 3))]
[(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 2)), (4, (1, 3)), (5, (2, 3)), (6, (1, 2, 3))]
[(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 2)), (4, (1, 3)), (5, (2, 3)), (6, (1, 2, 3))]

I'm running this with Python 3.8.2 on Arch Linux.我在 Arch Linux 上使用 Python 3.8.2 运行它。

Can someone explain why enumerate() does not loop with these inputs?有人可以解释为什么enumerate()不循环这些输入吗?

You exhausted your chained iterator with the first print statement.您用第一个print语句耗尽了链式迭代器。 The second and third did receive an empty iterator.第二个和第三个确实收到了一个空的迭代器。 If you want to see your expected output, you need to rebuild the chain for each run-through.如果你想看到预期的 output,你需要为每个贯穿重建链。

This is not specific to chain , nor to enumerate ;这不是特定的chain ,也不是enumerate you can get the same effect with你可以得到同样的效果

x = iter(range(10))

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

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