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.
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 )
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With