given a list

list=['beak','back','bear','kill','keel']

I'd like to perform a search with a wild card to return all words that match the pattern k**l for example. I can easily to this with the following:

regex=re.compile('k..l')
matches=[string for string in list if re.match(regex, string)]

However, I'd also like to access the index of the position of the matches and have something like that:

matches=kill, keel
locs=3,4

The reason why I want the indexes is that once the matches found I'd like to access a full row (containing other variables) in a df.

Thanks for your help.

有帮助吗?

解决方案

As stated in my comment, you can combine enumerate and zip to achieve your goal:

import re

lst=['beak','back','bear','kill','keel']
regex=re.compile('k..l')
locs, matches = zip(*[(idx, string) for idx, string in enumerate(lst) if re.match(regex, string)])
print(matches)
print(locs)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top