![](/img/trans.png)
[英]How to enumerate all cells in an Excel sheet with a (non-empty) value using openpyxl?
[英]Why is enumerate empty when passed a non-empty iterable?
据我了解, enumerate()
function 将遍历迭代中的每个项目。 但是,在下面的示例中,当给定一个非空的可迭代对象时,它根本不会循环。
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:
[(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))]
预期 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))]
我在 Arch Linux 上使用 Python 3.8.2 运行它。
有人可以解释为什么enumerate()
不循环这些输入吗?
您用第一个print
语句耗尽了链式迭代器。 第二个和第三个确实收到了一个空的迭代器。 如果你想看到你预期的 output,你需要为每个贯穿重建链。
这不是特定的chain
,也不是enumerate
; 你可以得到同样的效果
x = iter(range(10))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.