- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我们有以下代码:
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/
我有一个看起来像这样的类 Class myClass: def __init__(self, key, value): self.key = key self.
我正在编写一个返回自身修改的迭代器对象,我希望原始对象成为迭代过程的一部分,因此需要在修改之前返回它。 ...但是: 创建要返回的对象的深拷贝非常耗时。 对象有很多属性,所以定义辅助变量似乎不是一个优
我看到 next = __next__ 出现在 OOP 代码的多个地方。 这样做的目的是什么?即使没有这条线,它也适用于我。 class Iter: def __init__(self, va
我正在尝试模拟协程。因此,此模拟的 __next__() 和 close() 被调用。虽然模拟 close() 有效,但我无法模拟 __next__(): mock_coroutine = m
我正在阅读有关生成器和迭代器以及 __next__() 的作用的文章. '__next__' in dir(mygen) .是真的 '__next__' in dir(mylist) ,是假的 当我深
我正在编写双向链表的实现。为了遍历列表,我使用了类似的东西: class Node: """ A node in our linked list """ def __init__(se
我使用的是 Python 2.7。 按照惯例,__iter__、__init__、__str__ 等内置方法使用双下划线来标识它们。为什么 next() 函数没有这个? 它与这里的其他内置函数一起
我正在尝试为迭代器创建自己的类,并找到了这样一个示例: class OddNum: """Class to implement iterator protocol""" def __init_
UPDATE(反映最先进的知识水平)状态:2017-05-12 进行此更新的原因是,当我问这个问题时,我并不知道我发现了有关Python3如何“在幕后”工作的信息。 从所有得出的结论是: 如果您为迭代
我现在正在研究一个双向链表类,我的 next 和 iter 方法遇到了麻烦。这是我类(class)的一个项目,我已经提交了该项目,现在只想了解如何实际修复它以使其有用。 我希望我的代码做的是设置一个当
在 Python 3 中,通过定义 __iter__ 和 __next__ 方法使类同时成为可迭代对象和迭代器是标准过程。但是我很难解决这个问题。以这个创建一个只产生偶数的迭代器的例子为例: clas
我正在研究制作可迭代对象,我想知道这两个选项中的哪一个更像 pythonic/更好的方法,是没有区别还是我对使用 yield 的想法有误?对我来说,使用 yield 似乎更干净,而且显然它比使用 __
我正在使用 yield 在我的类中的 __next__() 函数中返回下一个值。但是它不返回下一个值,它返回生成器对象。 我正在尝试更好地理解迭代器和 yield。我可能做错了。 看看。 class
我从生成器收到了未知数量的后台处理记录。如果有更重要的工作,我就得停下来释放进程。 main 流程最好描述为: def main(): generator_source = generator
如果我们有以下代码: s = "stackoverflow" si = iter(s) si.__next__() # Would return s si.__next__() # Would ret
我对 python 迭代器有点迷茫。我偶尔会使用它们,但我不记得自己创建过一个。我从某个地方读到的,我不记得在哪里,像这样的代码: class Foo(object): def __init_
我想使用跳过某些元素的 __next__ 创建一个 Python 迭代器类。 例如,我在这里使用 yield 和 continue 实现了一个生成器,我希望它下面的迭代器类做完全相同的事情。 def
>>> s = 'spam' >>> s.__next__() 结果是:回溯(最近调用最后): 文件“”,第 1 行,位于 s._下一个_()AttributeError:“str”对象没有属性“_n
来自 Learning python 书第 5 版: Page 421, footnote2: Technically speaking, the for loop calls the interna
我是一名优秀的程序员,十分优秀!