问题描述
这比实际问题更像是编程练习:我正在寻找类似于append
行为的生成器表达式.
This is more a programming exercise than a real-world problem: I am looking for a generator expression that resembles the behavior of append
.
考虑:
def combine(sequence, obj):
for item in sequence:
yield item
yield obj
s = ''.join(combine(sequence, obj))
此生成器基本上类似于append
.在我的程序的工作流程中,以上步骤一样快
This generator basically resembles append
. In the workflow of my program the above is as fast as
sequence.append(obj)
s = ''.join(sequence)
我现在想知道是否有一个整洁的生成器表达式genexpr
与
I am now wondering if there is a neat generator expression genexpr
with
s = ''.join(genexpr)
类似于上面的append
行为,没有性能方面的警告.
that resembles the append
behavior above without performance caveats.
s = ''.join(_ for a in [sequence, [obj]] for _ in a)
表现不好.
推荐答案
尝试使用 itertools
模块中的chain
:
Try using chain
from itertools
module:
''.join(chain(sequence, [obj]))
如果您不想为obj
创建新的list
,则可以尝试以下操作:
If you don't want to create a new list
for obj
, then you may try this:
''.join(chain(sequence, repeat(obj,1)))
我会使用[obj]
,因为它更具可读性,并且我怀疑repeat
迭代器的开销要小于list
创建的开销.
I would use [obj]
as it's more readable and I doubt that repeat
iterator has a less overhead than list
creation.
这篇关于类似于附加行为的生成器表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!