python查找并替换列表项,如果子串存在[重复]

问题描述 投票:1回答:3

这个问题在这里已有答案:

我想替换包含某个子字符串的列表中的项目。在这种情况下,任何形式的包含“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)  
python string python-3.x list substring
3个回答
1
投票

any不会给你索引,并且在每次迭代时总是如此。所以放弃它......

我个人使用列表理解与三元组来决定保留原始数据或由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']

3
投票

简单的list comprehension

>>> ["NSW = 0" if "NSW" in ele else ele for ele in l]

#driver值:

IN :    l = ["abc 123", "acd 234", "NSW = 500", "stuff", "morestuff"]
OUT : ['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']

1
投票

另一解决方案:代码:

from __future__ import division, print_function, with_statement
my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]
for index in xrange(len(my_list)):
    if "NSW" in my_list[index]:
        my_list[index] = "NSW = 0"

print (my_list)  

输出:

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

或者您可以将列表理解用于以下目的:

码:

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

print ["NSW = 0" if "NSW" in _ else _ for _ in my_list]

输出:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']
© www.soinside.com 2019 - 2024. All rights reserved.