Python: get list indexes using regular expression?

前端 未结 3 1597
梦毁少年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')]
    

提交回复
热议问题