This question already has answers here:
Replace values in list using Python [duplicate]
                                
                                    (7个答案)
                                
                        
                                去年关闭。
            
                    
我想替换包含某个子字符串的列表中的项目。在这种情况下,包含“ NSW”(大写字母)的任何形式的项目都应替换为“ NSW = 0”。原始条目显示为“ NSW = 500”还是“ NSW = 501”都没关系。我可以找到列表项,但是以某种方式我无法在列表中找到该位置,因此我可以替换它?这是我想出的,但是我替换了所有项目:

from __future__ import division, print_function, with_statement
my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]
for index, i in enumerate(my_list):
    if any("NSW" in s for s in my_list):
        print ("found")
        my_list[index]= "NSW = 0"
print (my_list)

最佳答案

any不会为您提供索引,并且每次迭代都始终为true。放下...

我个人将使用具有三元数的列表理解来决定保留原始数据还是用NSW = 0代替:

my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]

result = ["NSW = 0" if "NSW" in x else x for x in my_list]


结果:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']

10-05 23:57