【问题标题】:Checkan iterable after expanding the iterations using zip?使用 zip 扩展迭代后检查可迭代?
【发布时间】:2015-12-05 18:40:25
【问题描述】:

如何在使用 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

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

【问题讨论】:

  • 你想对剩余的值做什么?
  • 我正在尝试从 x 或 y 中提取所有未迭代的剩余值。

标签: python list zip iterable try-except


【解决方案1】:

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

【讨论】:

  • 啊,我每天都从 SO 那里学到新东西。现在我知道 iterable 有 __length_hint__() 以及它的作用 =)
【解决方案2】:

你的意思是你不能尝试-except?

try:
    x.next()
except StopIteration:
    pass

【讨论】:

  • Ohhhh,StopIteration 不以 Error 结尾,但它仍然是内置关键字?
  • StopIteration 是迭代对象时引发的异常。这是 Python 告诉你没有更多项目的方式。
【解决方案3】:

根据您要实现的目标,如果您对 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

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2019-12-03
    相关资源
    最近更新 更多