【问题标题】:Searching for a keyword in a list of strings and replacing the entire string if it contains that keyword在字符串列表中搜索关键字并替换整个字符串(如果它包含该关键字)
【发布时间】:2020-12-11 02:03:55
【问题描述】:

我有一个字符串列表mylist,我想搜索每个字符串,看看它是否有某个关键字,假设关键字是"blue"。如果我在任何特定字符串中找到单词 blue,我想将该 整个 字符串更改为完全不同的字符串。到目前为止,我已经找到了一种方法来更改该特定字符串,然后在我的“for”循环中成功打印它,但是当我打印完整列表时,它不再被更改。这就是我的意思:

输入:

mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']

for i in mylist:
    if 'blue' in i:
        i = i.replace(str(i),'Found blue')
        print(i)
print(mylist)

输出:

Found blue

['my name is bob','my favorite color is blue', 'eggs are tasty']

如您所见,print(i) 替换了我想要的字符串,但是当我打印完整列表时实际列表没有改变

有没有办法以这种方式更改列表,还是我需要以不同的方式处理?

【问题讨论】:

    标签: python list replace


    【解决方案1】:

    您需要将其实际分配回列表because strings are immutable in Python:

    mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']
    
    for i in range(len(mylist)):
        if "blue" in mylist[i]:
            mylist[i] = "Found blue" # no need to use replace if you're going to change the whole string
    

    或者,您可以使用列表推导式或地图

    mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']
    mylist[:] = ["Found blue" if "blue" in i else i for i in mylist]
    
    # Or
    mylist = ['my name is bob','my favorite color is blue', 'eggs are tasty']
    mylist[:] = list(map(lambda i: "Found blue" if "blue" in i else i, mylist))
    

    【讨论】:

    • 我的意思是为您的答案添加更多上下文。告诉人们为什么他们需要做某事的答案比仅仅告诉他们做什么该做的答案更有帮助。
    猜你喜欢
    • 2019-09-17
    • 2021-07-09
    • 1970-01-01
    • 2018-07-23
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    相关资源
    最近更新 更多