简体   繁体   English

通过正则表达式获取列表中字典项的索引

[英]Get index of dictionary item in list by regexp

I have a list: 我有一个清单:

[
  {
    'avail': 'blabla',
    'rep_main': 'qweqwe',
    ....
  },
  {
    'avail': 'asdasd',
    'rep_main': 'zxczxc',
    ....
  },
  ...
]

I want to get the index of the item by means of regexp That's like a version without regexp: 我想通过regexp获取项目的索引,就像没有regexp的版本一样:

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

If pattern is the pattern and re is the re module : 如果pattern是pattern而rere模块

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

You can use re.search instead of re.match . 您可以使用re.search而不是re.match

enumerate is a convenient built-in function that lets you use indexes without that for i in range(len(mylist)) ugliness. enumerate是一种方便的内置函数,可让您使用索引而不使用for i in range(len(mylist))丑陋的for i in range(len(mylist))

Note: the expression above obviously evaluates to a list. 注意:上面的表达式显然是一个列表。 .index() method returns the first matching index. .index()方法返回第一个匹配的索引。 To achieve that, write: 为此,请编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM