简体   繁体   中英

Find strings from a list starting with strings in another list

I have two list listOne & listTwo

eg

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?

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)]

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM