Python: get list indexes using regular expression?

前端 未结 3 1590
梦毁少年i
梦毁少年i 2021-01-31 16: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 t

相关标签:
3条回答
  • 2021-01-31 16:59

    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')]
    
    0 讨论(0)
  • 2021-01-31 17:02

    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$")
    
    0 讨论(0)
  • 2021-01-31 17:18

    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.

    0 讨论(0)
提交回复
热议问题