Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use list to filter another list in python

Tags:

python

I have a list:

data_list = ['a.1','b.2','c.3']

And I want to retrieve only strings that start with strings from another list:

test_list = ['a.','c.']

a.1 and c.3 should be returned.

I suppose I could use a double for-loop:

for data in data_list:
    for test in test_list:
       if data.startswith(test):
           # do something with item

I was wondering if there was something more elegant and perhaps more peformant.

like image 459
Andy Arismendi Avatar asked Nov 30 '22 03:11

Andy Arismendi


2 Answers

str.startswith can also take a tuple (but not a list) of prefixes:

test_tuple=tuple(test_list)
for data in data_list:
    if data.startswith(test_tuple):
        ...

which means a simple list comprehension will give you the filtered list:

matching_strings = [ x for x in data_list if x.startswith(test_tuple) ]

or a call to filter:

import operator
f = operator.methodcaller( 'startswith', tuple(test_list) )
matching_strings = filter( f, test_list )
like image 172
chepner Avatar answered Dec 06 '22 16:12

chepner


Simply use filter with a lambda function and startswith:

data_list = ['a.1','b.2','c.3']
test_list = ('a.','c.')

result = filter(lambda x: x.startswith(test_list), data_list)

print(list(result))

Output:

['a.1', 'c.3']
like image 26
aldeb Avatar answered Dec 06 '22 15:12

aldeb