开发者

Changing python immutable type while iterating through a mutable container such as list

开发者 https://www.devze.com 2023-01-25 21:44 出处:网络
I am wondering what is the most pythonic way to do the following and have it work: strings = [\'a\',\'b\']

I am wondering what is the most pythonic way to do the following and have it work:

strings = ['a','b']

for s in strings:  
    s = s+'c'

obviously this doesn't work in python but the result that I want to acheive is

strings = ['ac','bc']

Whats the most pythonic way to achieve this kind of result?

Than开发者_C百科ks for the great answers!


strings = ['a', 'b']
strings = [s + 'c' for s in strings]


You can use list comprehension to create a list that has these values: [s + 'c' for s in strings]. You can modify the list in-place like this:

for i, s in enumerate(strings):
    strings[i] = s + 'c'

But I found that quite often, in-place modification is not needed. Look at your code to see if this applies.


You can use map function for that.

strings = ['a', 'b']
strings = map(lambda s: s + 'c', strings)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号