[英]How to get the current value of a Python iterator - dereferencing an iterator without incrementing
[英]How to get the item currently pointed at by iterator without incrementing?
有没有办法在不增加迭代器本身的情况下让 python 中的迭代器指向该项目? 例如,我将如何使用迭代器实现以下内容:
looking_for = iter(when_to_change_the_mode)
for l in listA:
do_something(looking_for.current())
if l == looking_for.current():
next(looking_for)
迭代器无法获取当前值。 如果您想要那样,请自己保留对它的引用,或者包装您的迭代器以便为您保留它。
looking_for = iter(when_to_change_the_mode)
current = next(looking_for)
for l in listA:
do_something(current)
if l == current:
current = next(looking_for)
问题:如果在迭代器的末尾怎么办? next
函数允许使用默认参数。
我认为没有内置的方法。 将有问题的迭代器包装在缓冲一个元素的自定义迭代器中非常容易。
当我需要这样做时,我通过创建如下类来解决它:
class Iterator:
def __init__(self, iterator):
self.iterator = iterator
self.current = None
def __next__(self):
try:
self.current = next(self.iterator)
except StopIteration:
self.current = None
finally:
return self.current
这样您就可以像使用标准迭代器一样使用 next(itr),并且可以通过调用 itr.current 获取当前值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.