在Python中将相同的字符串追加到字符串列表 [英] Appending the same string to a list of strings in Python

查看:222
本文介绍了在Python中将相同的字符串追加到字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个字符串,并将其附加到列表中包含的每个字符串中,然后创建一个包含已完成字符串的新列表.示例:

I am trying to take one string, and append it to every string contained in a list, and then have a new list with the completed strings. Example:

list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'

*magic*

list2 = ['foobar', 'fobbar', 'fazbar', 'funkbar']

我尝试了循环,并尝试了列表理解,但这是垃圾.一如既往的任何帮助,不胜感激.

I tried for loops, and an attempt at list comprehension, but it was garbage. As always, any help, much appreciated.

推荐答案

最简单的方法是使用列表理解:

The simplest way to do this is with a list comprehension:

[s + mystring for s in mylist]

请注意,我避免使用诸如list之类的内置名称,因为这样会掩盖或隐藏内置名称,这非常不好.

Notice that I avoided using builtin names like list because that shadows or hides the builtin names, which is very much not good.

此外,如果您实际上不需要列表,而只需要一个迭代器,则生成器表达式可能会更有效(尽管在短列表中这并不重要):

Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):

(s + mystring for s in mylist)

这些功能非常强大,灵活且简洁.每个优秀的python程序员都应该学会使用它们.

These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.

这篇关于在Python中将相同的字符串追加到字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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