Reputation: 39
I'm trying to write simple logic that will look for words in one list that start with words from other list. For example:
a = ["let","test","g"]
b = ["letter", "testing","good","egg","protest"]
should return: letter, testing, good
.
I have dabbled with .startswith()
but it seems to be unable to use entire list for searching. Also tried with:
if any(i in a for i in b):
but I am unable to get any results with it.
Upvotes: 0
Views: 1215
Reputation: 1846
I prefer using the itertools
module for such cases:
>>> [value for (start, value) in itertools.product(a,b) if value.startswith(start)]
['letter', 'testing', 'good']
Upvotes: 0
Reputation: 59112
If you want to find the first element in b
that starts with some string, you can use next
.
word = next(bword for bword in b if bword.startswith(aword))
In case there is no such word in b
, you can supply a default value
word = next((bword for bword in b if bword.startswith(aword)), None)
To apply to that to each element of a
, you could use a list comprehension.
words = [next((bword for bword in b if bword.startswith(aword)), None) for aword in a]
This produces:
['letter', 'testing', 'good']
Upvotes: 1
Reputation: 41168
str.startswith()
accepts a tuple:
>>> a = ["let","test","g"]
>>> b = ["letter", "testing","good","egg","protest"]
>>> a = tuple(a)
>>> [item for item in b if item.startswith(a)]
['letter', 'testing', 'good']
Upvotes: 9
Reputation: 11280
You can do it with list comprehension:
>>> [y for x in a for y in b if y.startswith(x)]
['letter', 'testing', 'good']
You need to iterate over both of the lists, and then check if the elements from the list a
are the start of the objects in list b
.
If you just need it for conditional testing, you better off with generators. This will stop on the first match in the list:
>>> gen_exp = (y for x in a for y in b if y.startswith(x))
>>> if any(gen_exp):
__ your logic here __
Upvotes: 4