gpt4 book ai didi

python - 使用 zip 扩展迭代后检查可迭代?

转载 作者:行者123 更新时间:2023-11-28 20:41:45 25 4
gpt4 key购买 nike

如何在使用 zip 扩展迭代后检查可迭代对象是否相同大小? 例如

>>> x = iter([1,2,3])
>>> y = iter([5,6,7,8])
>>> for i,j in zip(x,y):
... print i,j
...
1 5
2 6
3 7

在用完可迭代对象后执行 next(x) 会引发错误,但我无法尝试 - 除了它,因为它不是 Error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

有什么方法可以一次性完成检查吗?

最佳答案

next 也有一个默认值,因此您可以简单地使用它:

if next(x, None):
# x is not empty

只需确保使用不会出现在您的可迭代对象中的默认值即可。

也可以使用__length_hint__:

In [4]: x = iter([1, 2, 3])

In [5]: y = iter([5, 6, 7, 8])

In [6]: for i, j in zip(x, y):
...: print(i, j)
...:
(1, 5)
(2, 6)
(3, 7)

In [7]: x.__length_hint__()
Out[7]: 0

In [8]: y.__length_hint__()
Out[8]: 1

关于python - 使用 zip 扩展迭代后检查可迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com