python - 如何在 python 中对迭代器调用 __next__ n 次

标签 python iterator

如果我们有以下代码:

s = "stackoverflow"
si = iter(s)
si.__next__() # Would return s
si.__next__() # Would return t
si.__next__() # Would return a

有没有一种不使用循环的方法,我可以通过一次调用 __next__() 获得 "a"。所以基本上我想调用 __next__() 三次并获得第三个值。 (注意一定要用迭代器,不能只用切片)

谢谢

最佳答案

您可以使用 itertools.islice :

>>> from itertools import islice
>>> si = iter(s)
>>> next(islice(si, 2, 3))
'a'

关于python - 如何在 python 中对迭代器调用 __next__ n 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36855889/

相关文章:

python - sympy 矩阵中的 sympy 矩阵在替换时保持未计算状态

python - 从 ctypes 数组中获取数据到 numpy

c++ - 返回迭代器与松散耦合

Python MySQLdb : Iterating over a cursor

c++ - 同时访问列表中的元素及其后继元素

python - 葡萄牙语编码 ã、ê、ç、á

python - 如何在 pygame 上使用字体系列?

Python chr() 函数输出不正确

python - 您如何使用 python 遍历收件箱中的每封电子邮件?

rust - 检测按顺序发生的字符串切片的重复元素