reservoirinvest
reservoirinvest

Reputation: 1777

Find words that do not match a list in a list

Would like to find words in a list that do not match words in a master list.

Code is:

master = ['This', 'is', 'a', 'pond', 'full', 'of', 'good', 'words']
dontfindme = ['po', 'go', 'a']

Expected result is: ['This', 'is', 'full', 'of', 'words']

Can do:

list(set(master).difference(set([m for m in master for df in dontfindme if df in m])))

...but it screws up the order.

Is there a better way using just list comprehension?

Upvotes: 0

Views: 78

Answers (2)

Phoenix
Phoenix

Reputation: 4284

You can use filter() python built-in method.

filter(function, iterable)

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

def _filter():
    master = ['This', 'is', 'a', 'pond', 'full', 'of', 'good', 'words']
    dontfindme = ['po', 'go', 'a']

    return list(filter(lambda x: all([item not in x for item in dontfindme]), master))


if __name__ == '__main__':
    print(_filter())

Output:

['This', 'is', 'full', 'of', 'words']

Upvotes: 0

seymourgoestohollywood
seymourgoestohollywood

Reputation: 1167

master = ['This', 'is', 'a', 'pond', 'full', 'of', 'good', 'words']
dontfindme = ['po', 'go', 'a']

result = [x for x in master if all(item not in x for item in dontfindme)]
print(result)

Gives:

['This', 'is', 'full', 'of', 'words']

Upvotes: 3

Related Questions