在迭代可变容器(例如列表)时更改 python 不可变类型
我想知道执行以下操作并使其工作的最Pythonic方法是什么:
strings = ['a','b']
for s in strings:
s = s+'c'
显然这在Python中不起作用,但我想要实现的结果是
字符串 = ['ac','bc']
实现这种结果最Pythonic的方法是什么?
感谢您的精彩回答!
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?
Thanks for the great answers!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用列表理解来创建具有以下值的列表:
[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: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.