Python 通过regexp获取列表中字典项的索引

Python 通过regexp获取列表中字典项的索引,python,regex,list,dictionary,indexing,Python,Regex,List,Dictionary,Indexing,我有一份清单: [ { 'avail': 'blabla', 'rep_main': 'qweqwe', .... }, { 'avail': 'asdasd', 'rep_main': 'zxczxc', .... }, ... ] 我想通过regexp获得项目的索引 这就像没有regexp的版本: [list['rep_main'] for elem in list].index('qweqwe') 如果pattern是

我有一份清单:

[
  {
    'avail': 'blabla',
    'rep_main': 'qweqwe',
    ....
  },
  {
    'avail': 'asdasd',
    'rep_main': 'zxczxc',
    ....
  },
  ...
]
我想通过regexp获得项目的索引 这就像没有regexp的版本:

[list['rep_main'] for elem in list].index('qweqwe')

如果
pattern
是模式,
re
是:

你可以用

是一个方便的内置函数,它允许您对范围内的i(len(mylist))使用索引而不使用

注意:上面的表达式的计算结果显然是一个列表
.index()
方法返回第一个匹配的索引。要实现这一点,请编写:

next(i for i, elem in enumerate(mylist) if re.match(pattern, elem['rep_main']))

如果
pattern
是模式,
re
是:

你可以用

是一个方便的内置函数,它允许您对范围内的i(len(mylist))使用索引而不使用

注意:上面的表达式的计算结果显然是一个列表
.index()
方法返回第一个匹配的索引。要实现这一点,请编写:

next(i for i, elem in enumerate(mylist) if re.match(pattern, elem['rep_main']))

[i for i,elem in enumerate(list)if re.search('qwe$',elem['rep_main'])我有以下错误:“TypeError:expected string或buffer”@user1372305很高兴它有帮助:)[i for i,elem in enumerate(list)if re.search('qwe$,elem['rep_main'])]我有以下错误:“typerror:expected string或buffer”@user1372305很高兴它有帮助:)