39

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?

3
  • 4
    That's not a regular expression. Commented Nov 10, 2010 at 15:28
  • 2
    Regular expressions aren't fuzzy, either. Just the opposite, actually: they're very strict and precise. Commented Nov 10, 2010 at 16:02
  • That's not a regex Commented Jun 22, 2023 at 20:56

3 Answers 3

71

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')]
Sign up to request clarification or add additional context in comments.

2 Comments

This answer should have been selected as the answer.
I still find it odd that this is the easiest way to do this fairly common operation in python. In R it would just be grep('berry$', berry_idx). Is there no module that implements a cleaner way to search and get integer locations?
34

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.

Comments

3

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$")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.