In Python, how do you get the position of an item in a list (using list.index
) using fuzzy matching?
For example, how do I get the indexes of all fruit of the form *berry
in the following list?
fruit_list = ['raspberry', 'apple', 'strawberry'] # Is it possible to do something like the following? berry_fruit_at_positions = fruit_list.index('*berry')
Anyone have any ideas?
Python List index() Python index() is an inbuilt function in Python, which searches for a given element from the start of the list and returns the index of the first occurrence.
span() method returns a tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1). Parameters: group (optional) By default this is 0. Return: A tuple containing starting and ending index of the matched string.
Finditer method finditer() works exactly the same as the re. findall() method except it returns an iterator yielding match objects matching the regex pattern in a string instead of a list. It scans the string from left to right, and matches are returned in the iterator form.
With regular expressions:
import re fruit_list = ['raspberry', 'apple', 'strawberry'] berry_idx = [i for i, item in enumerate(fruit_list) if re.search('berry$', item)]
And without regular expressions:
fruit_list = ['raspberry', 'apple', 'strawberry'] berry_idx = [i for i, item in enumerate(fruit_list) if item.endswith('berry')]
Try:
fruit_list = ['raspberry', 'apple', 'strawberry'] [ i for i, word in enumerate(fruit_list) if word.endswith('berry') ]
returns:
[0, 2]
Replace endswith
with a different logic according to your matching needs.
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