类似于附加行为的生成器表达式 [英] Generator expression that resembles the behavior of append

查看:63
本文介绍了类似于附加行为的生成器表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这比实际问题更像是编程练习:我正在寻找类似于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.

这篇关于类似于附加行为的生成器表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆