当列表中的元素在字符串中时,我想从字符串中删除列表中的元素

时间:2020-04-29 10:07:20

标签: python list

假设

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

我想从列表a中删除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']

请帮助我

3 个答案:

答案 0 :(得分:3)

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方法,然后将其添加到结果列表中

答案 1 :(得分:1)

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

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

print(result)

输出:

['wi', 'wz', 'r']

答案 2 :(得分:1)

其他解决方案可为您提供所需的东西,因此这里有些有趣。您可以将functools.reduce与自定义功能一起使用。

from functools import reduce

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


def remove(x, y):
    return x.replace(y, '')

out = [reduce(remove, a, i) for i in b]

给予

['wi', 'wz', 'r', 'ksw', 'erer']

编辑: 可能最不清晰的写法是使用带有lambda的单线:)

[reduce(lambda x, y: x.replace(y, ''), a, i) for i in b]