如何在一个字符串中删除字符(如果存在于另一个Python中)

时间:2016-03-26 14:30:53

标签: python string

我试图创建一个函数来删除一个字符串中的字符(如果存在于另一个字符串中)。

例如:

l1 = [' a',' b',' c',' d',' e' ,' f']

l2 = [' b',' c',' e']

我希望它能够返回[' a'' d'' f']

我想在一个函数中使用它。谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

这是一个简单的列表补偿方法:

def f(l1, l2):
    return [x for x in l1 if x not in l2]

l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = ['b', 'c', 'e']
print(f(l1, l2))
>>> ['a', 'd', 'f']

以下是一些(使用过滤器):

f = lambda l1, l2: list(filter(lambda elem: elem not in l2, l1))

如果要修改原始列表:

def f(l1, l2):
    for elem in l2:
        l1.remove(elem)
    return l1

l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = ['b', 'c', 'e']
print(l1) # Prints ['a', 'b', 'c', 'd', 'e', 'f']
print(f(l1, l2)) # Modifies l1 and returns it, printing ['a', 'd', 'f']
print(l1) # Prints ['a', 'd', 'f'] (notice the list has been modified)

如果你需要字符串(而不是你问题中列出的列表),这里还有另一个lambda:

s1 = 'abcdef'
s2 = 'bce'
# Both of the below work with strings and lists alike (and return a string)
fn = lambda s1, s2: "".join(char for char in s1 if char not in s2)
# Or, using filter:
fn = lambda s1, s2: "".join(filter(lambda char: char not in s2, s1))

print(fn(s1, s2)
>>> 'adf'

答案 1 :(得分:0)

这应该有效

def subtract_list(list1, list2):
    return list(set(list1) - set(list2))

答案 2 :(得分:-1)

您可以使用list comprehension

>>> l1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> l2 = ['b', 'c', 'e']
>>> l3 = [i for i in l1 if i not in l2]
>>> l3
['a', 'd', 'f']