就地替换python中列表中所有出现的元素 [英] In-place replacement of all occurrences of an element in a list in python
本文介绍了就地替换python中列表中所有出现的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个列表:
myl = [1, 2, 3, 4, 5, 4, 4, 4, 6]
就地(双重强调)用替换所有
?4
的最有效和最简单的pythonic方法是什么?>44
What is the most efficient and simplest pythonic way of in-place (double emphasis) replacement of all occurrences of 4
with 44
?
我也很好奇为什么没有 standard
这样做的方法(特别是当 strings
有一个 not-in-place replace
方法)?
I'm also curious as to why there isn't a standard
way of doing this (especially, when strings
have a not-in-place replace
method)?
推荐答案
我们可以用 enumerate
遍历列表,并用新值替换旧值,就像这样
We can iterate over the list with enumerate
and replace the old value with new value, like this
myl = [1, 2, 3, 4, 5, 4, 4, 4, 6]
for idx, item in enumerate(myl):
if item == 4:
myl[idx] = 44
print myl
# [1, 2, 3, 44, 5, 44, 44, 44, 6]
这篇关于就地替换python中列表中所有出现的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文