this question has answer here:
- remove elements occur in 1 list another 5 answers
i'm trying create function remove characters 1 string if present in another.
for example:
l1 = ['a', 'b', 'c', 'd', 'e', 'f']
l2 = ['b', 'c', 'e']
i want return ['a', 'd', 'f']
i have within function. thank help!
here's simple list comp approach:
def f(l1, l2): return [x 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']
here few more (using filter can say):
f = lambda l1, l2: list(filter(lambda elem: elem not in l2, l1))
if want modify original list:
def f(l1, l2): 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 , returns it, printing ['a', 'd', 'f'] print(l1) # prints ['a', 'd', 'f'] (notice list has been modified)
if need strings (and not lists posted in question), here's lambda:
s1 = 'abcdef' s2 = 'bce' # both of below work strings , lists alike (and return string) fn = lambda s1, s2: "".join(char 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'
Comments
Post a Comment