Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: get list indexes using regular expression?

Tags:

python

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?

like image 517
AP257 Avatar asked Nov 10 '10 15:11

AP257


People also ask

What is the index in a python list?

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.

What is the use of SPAN () in regular expression?

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.

How do I use Finditer in Python?

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.


2 Answers

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')] 
like image 78
Steven Rumbalski Avatar answered Sep 27 '22 23:09

Steven Rumbalski


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.

like image 20
eumiro Avatar answered Sep 28 '22 01:09

eumiro