황준석
황준석

Reputation: 53

I want to remove elements from the list from the string when the elements of the list are in the string

Suppose

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

I want to remove any of the characters listed in a from list b. result should be `['wi','wz','r','ksh','erer']

This is the code I tried :

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

But this code returns result = ['ksw','erer']

please help me

Upvotes: 4

Views: 72

Answers (3)

tomjn
tomjn

Reputation: 5389

Other solutions give you what you want so here is one for a bit of fun. You can use functools.reduce with a custom function.

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]

giving

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

Edit: Probably the least clear way you could write this would be as a one-liner with a lambda :)

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

Upvotes: 1

kynnemall
kynnemall

Reputation: 888

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

The any function in your code is unnecessary. You need to loop through both lists, then check if your substring is in the string of the other list, call the replace method on your word containing the substring, and then add it to your list of results

Upvotes: 3

Rajarishi Devarajan
Rajarishi Devarajan

Reputation: 581

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)

Output:

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

Upvotes: 1

Related Questions