Python: get list indexes using regular expression?
Question:
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?
Answers:
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.
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')]
with a function :
import re
fruit_list = ['raspberry', 'apple', 'strawberry']
def grep(yourlist, yourstring):
ide = [i for i, item in enumerate(yourlist) if re.search(yourstring, item)]
return ide
grep(fruit_list, "berry$")
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?
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.
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')]
with a function :
import re
fruit_list = ['raspberry', 'apple', 'strawberry']
def grep(yourlist, yourstring):
ide = [i for i, item in enumerate(yourlist) if re.search(yourstring, item)]
return ide
grep(fruit_list, "berry$")