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

查看:31
本文介绍了将相同的字符串附加到 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:

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

*magic*

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

我尝试了 for 循环,并尝试了列表理解,但它很垃圾.一如既往,任何帮助,非常感谢.

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天全站免登陆