将下一个n次迭代分配给元组

时间:2016-04-07 08:53:45

标签: python

有更复杂的方法吗?

node = next(iterable), next(iterable), next(iterable)

1 个答案:

答案 0 :(得分:4)

您可以使用itertools.islice从可迭代项中选择项目。请注意,迭代器是可迭代的,但并非每个iterable都是具有next(或Python3中的__next__)方法的迭代器。

>>> from itertools import islice
>>> iterator = (x for x in ('a', 'b', 'c', 'd', 'e'))
>>> tuple(islice(iterator, 3))
('a', 'b', 'c')

或者,一个简单的理解:

>>> iterator = (x for x in ('a', 'b', 'c', 'd', 'e'))
>>> tuple(next(iterator) for _ in range(3))
('a', 'b', 'c')

名称_对于解释器没有特殊含义(在交互式会话之外,它存储最后执行的语句的结果)但是被Python程序员注意为一次性变量的名称。 / p>

相关问题