简体   繁体   中英

Replacing particular elements in a list

Code:

>>> mylist = ['abc','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 (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]

使用带有三元运算/ 条件表达式列表推导:

['XXX' if item == 'abc' else item for item in mylist]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM