简体   繁体   English

Python,在列表中的每个项目上附加字符串

[英]Python, Appending string on each item on the list

I have a code that concatenates a string 'lst' on each item of the list. 我有一个代码连接列表中每个项目的字符串'lst'。

    i = 0
    lim = len(lst)
    while i < lim:
        lst[i] = 'lst%s' % (lst[i])
        i += 1

Is there a faster way of doing this? 有更快的方法吗?

This will modify the original lst object: 这将修改原始的lst对象:

lst[:] = ['lst%s' % item for item in lst]

or using the new style string formatting: 或使用新样式字符串格式:

lst[:] = ['lst{}'.format(item) for item in lst]

使用列表推导切片分配:

lst[:] = ['lst' + x for x in lst]

这是一个地图版本

lst = map(lambda x: 'lst%s' % x, lst)

A map version for fun 一个有趣的地图版本

>>> lst=['foo', 'bar', 'baz']
>>> map('lst'.__add__, lst)
['lstfoo', 'lstbar', 'lstbaz']

But more seriously, you can assign to a slice from a generator expression 但更严重的是,您可以从生成器表达式分配切片

>>> lst[:] = ('lst{}'.format(x) for x in lst)
>>> lst
['lstfoo', 'lstbar', 'lstbaz']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM