简体   繁体   English

替换列表中的特定元素

[英]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' . 在这里,我尝试用'XXX'替换所有出现的'abc' 'XXX' Is there a shorter way to do this? 有没有更短的方法来做到这一点?

Instead of using an explicit for loop, you can use a list comprehension . 您可以使用列表推导,而不是使用显式的for循环。 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 (v == 'abc') ? 'XXX' : v in other languages. (v == 'abc') ? 'XXX' : v用其他语言。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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