开发者

Replacing particular elements in a list

开发者 https://www.devze.com 2023-04-10 06:04 出处:网络
Code: >>> mylist = [\'开发者_如何学Pythonabc\',\'def\',\'ghi\'] >>> mylist [\'abc\', \'def\', \'ghi\']

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号