In-place replacement of all occurrences of an elem

2019-01-25 09:54发布

问题:

This question already has an answer here:

  • Replace values in list using Python 7 answers

Assume I have a list:

myl = [1, 2, 3, 4, 5, 4, 4, 4, 6]

What is the most efficient and simplest pythonic way of in-place (double emphasis) replacement of all occurrences of 4 with 44?

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)?

回答1:

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]


回答2:

myl[:] = [x if x != 4 else 44 for x in myl]

Perform the replacement not-in-place with a list comprehension, then slice-assign the new values into the original list if you really want to change the original.



回答3:

for  item in myl:
   if item ==4:
      myl[myl.index(item)]=44


回答4:

while True:
    try:
        myl[myl.index(4)] = 44
    except:
        break

The try-except approach, although more pythonic, is less efficient. This timeit program on ideone compares at least two of the answers provided herein.