Python:使用正则表达式获取列表索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4146009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:27:23  来源:igfitidea点击:

Python: get list indexes using regular expression?

python

提问by AP257

In Python, how do you get the position of an item in a list (using list.index) using fuzzy matching?

在 Python 中,如何list.index使用模糊匹配(使用)获取项目在列表中的位置?

For example, how do I get the indexes of all fruit of the form *berryin the following list?

例如,如何获取*berry以下列表中所有水果的索引?

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?

谁有想法?

采纳答案by eumiro

Try:

尝试:

fruit_list = ['raspberry', 'apple', 'strawberry']
[ i for i, word in enumerate(fruit_list) if word.endswith('berry') ]

returns:

返回:

[0, 2]

Replace endswithwith a different logic according to your matching needs.

endswith根据您的匹配需求替换为不同的逻辑。

回答by Steven Rumbalski

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')]

回答by Dorian Grv

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