python字符串与列表的相同,在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]

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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值