使用 zip 扩展迭代后检查可迭代?
Checkan iterable after expanding the iterations using zip?
如何在使用zip扩展迭代后检查一个iterable是否相同大小?例如
>>> 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
有什么方法可以一次完成检查吗?
什么意思你不能尝试-except?
try:
x.next()
except StopIteration:
pass
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
根据您想要实现的目标,如果您对 itreables 中的所有值感兴趣,您可以考虑使用 itertools.izip_longest
而不是 zip
:
>>> import itertools
>>> x = iter([1,2,3])
>>> y = iter([5,6,7,8])
>>> for i, j in itertools.izip_longest(x, y, fillvalue=None):
... print i, j
...
1 5
2 6
3 7
None 8
如何在使用zip扩展迭代后检查一个iterable是否相同大小?例如
>>> 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
有什么方法可以一次完成检查吗?
什么意思你不能尝试-except?
try:
x.next()
except StopIteration:
pass
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
根据您想要实现的目标,如果您对 itreables 中的所有值感兴趣,您可以考虑使用 itertools.izip_longest
而不是 zip
:
>>> import itertools
>>> x = iter([1,2,3])
>>> y = iter([5,6,7,8])
>>> for i, j in itertools.izip_longest(x, y, fillvalue=None):
... print i, j
...
1 5
2 6
3 7
None 8