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)
精彩评论