HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Find all strings in list which have keywords in it from another list

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
allanotherkeywordsfindwhichlistfromstringshave

Problem

I a list of strings A and a list of keywords B. Now I want to return all strings from list A which have all keywords from B in it as a new list.

def string_search(strings, keys):
    res = []
    for s in strings:
        full = True
        for k in keys:
            if not(k in s):
                full = False
                break
        if full == True:
            res.append(s)
    return res


In which way could I improve this code? I ask purely out of curiosity, since it works perfectly fine and it is not the bottleneck of my processing chain.

Solution

Your general coding style is very readable.
You stick to PEP8 and your function and the variables are named reasonably.
You could optimize your code by using the built-in functions filter and all:

def string_search(strings, keys):
    return filter(lambda string: all(key in string for key in keys), strings)


Also do not use if var == True: but if var: instead.

Code Snippets

def string_search(strings, keys):
    return filter(lambda string: all(key in string for key in keys), strings)

Context

StackExchange Code Review Q#147396, answer score: 6

Revisions (0)

No revisions yet.