Code:
>>> mylist = ['开发者_如何学Pythonabc','def','ghi']
>>> mylist
['abc', 'def', 'ghi']
>>> for i,v in enumerate(mylist):
... if v=='abc':
... mylist[i] = 'XXX'
...
>>> mylist
['XXX', 'def', 'ghi']
>>>
Here, I try to replace all the occurrences of 'abc'
with 'XXX'
. Is there a shorter way to do this?
Instead of using an explicit for loop, you can use a list comprehension. This allows you to iterate over all the elements in the list and filter them or map them to a new value.
In this case you can use a conditional expression. It is similar to (v == 'abc') ? 'XXX' : v
in other languages.
Putting it together, you can use this code:
mylist = ['XXX' if v == 'abc' else v for v in mylist]
Use a list comprehension with a ternary operation / conditional expression:
['XXX' if item == 'abc' else item for item in mylist]
精彩评论