Leem.fin
Leem.fin

Reputation: 42602

Find strings from a list starting with strings in another list

I have two list listOne & listTwo

e.g.

listOne could contain 'about', 'day', 'school'

listTwo could contain 'a','c','da','z'

I want to find out all the elements in listOne which start with characters from elements in listTwo. The output with above example is 'about' and 'day'

I try to implement it with following code:

for elem1 in listTwo:
    for elem2 in listOne:
        if elem2.startswith(elem1):
            result.append(elem2)

but I feel it nested too much. Is there a more elegant way to achieve it in Python?

Upvotes: 1

Views: 309

Answers (2)

mgilson
mgilson

Reputation: 309929

The way that you're doing it is fine. It's easy to read/understand, etc.

However, if you really want, you can probably condense it down using itertools.product:

from itertools import product
result = [elem2 for elem1, elem2 in product(listTwo, listOne) if elem2.startswith(elem1)]

Upvotes: 1

gaganso
gaganso

Reputation: 3011

You can pass a tuple to str.startswith method.

From the doc:

str.startswith(prefix[, start[, end]]): Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

But this is supported in Python 2.5+

tuple_listTwo = tuple(listTwo)

[ele for ele in listOne if ele.startswith(tuple_listTwo)]

Output:

['day', 'about']

Upvotes: 1

Related Questions