有更复杂的方法吗?
node = next(iterable), next(iterable), next(iterable)
您可以使用itertools.islice
从迭代中选择项目。请注意,迭代器是可迭代的,但并不是每个可迭代的都是具有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程序员注意到它是一个一次性变量的名称。