首页 > 解决方案 > 当列表的元素在字符串中时,我想从字符串中删除列表中的元素

问题描述

认为

a = ['ab','bcd','efg','h']
b = ['wiab','wbcdz','rh','ksw','erer']

我想a从 list中删除任何列出的字符b。结果应该是 `['wi','wz','r','ksh','erer']

这是我尝试过的代码:

result = []
for i in b:
    if not any(word in i for word in a):
        result.append(word)

但是这段代码返回 result = ['ksw','erer']

请帮我

标签: pythonlist

解决方案


def function(a,b):
    result = []
    for i in a:
        for word in b:
            if i in word:
                result.append(word.replace(i,''))
    return result

您的代码中的any函数是不必要的。您需要遍历两个列表,然后检查您的子字符串是否在另一个列表的字符串中,在replace包含子字符串的单词上调用该方法,然后将其添加到结果列表中


推荐阅读