gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:47:12 26 4
gpt4 key购买 nike

如果我们有以下代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com