生成器表达式是一个非常有用的工具,与列表理解相比有着巨大的优势,即它不为新数组分配内存。在
对于生成器表达式,我面临的问题是,我只能使用一次这样的生成器一次,这最终导致我只能编写列表理解:
>>> names = ['John', 'George', 'Paul', 'Ringo']
>>> has_o = (name for name in names if 'o' in name)
>>> for name in has_o:
... print(name.upper())
...
JOHN
GEORGE
RINGO
>>> for name in has_o:
... print(name.lower())
...
>>>
上面的代码说明了生成器表达式如何只能使用一次。当然,这是因为生成器表达式返回生成器的一个实例,而不是定义一个可以反复实例化的生成器函数。在
是否有一种方法可以在每次使用生成器时克隆它,以使其可重用,或者使生成器表达式语法返回生成器函数而不是单个实例?在
^{} 允许您从一个iterable生成多个迭代器:
输出:
^{pr2}$使其成为
lambda
:
^{pr2}$lambda
是一个单行程序,每次都返回一个新的生成器。在这里,我选择能够传递输入列表,但是如果它是固定的,您甚至不需要参数:在最后一种情况下,请注意这样一个事实:如果
names
发生更改或被重新分配,lambda
将使用新的names
对象。可以使用默认值技巧修复名称重新指定:您可以通过使用默认值和复制技巧来修复
names
的后续修改(当您认为您的第一个目标是避免创建列表时,这并不是非常有用:):(现在选择:)
好吧,各位,这里有一个代码,可以让您的迭代器可重用。 它在每次迭代后自动重置自己,这样您就不必担心任何事情。 效率有多高,好吧,它是两个方法调用(一个是针对tee()的next(),它反过来又调用迭代器本身的next()),另一个是在原始迭代器之上的try except块。 你必须决定一个微小的速度损失是可以的还是使用lambda重建迭代器,如其他答案所示。在
相关问题 更多 >
编程相关推荐