【问题标题】:Get index of dictionary item in list by regexp通过正则表达式获取列表中字典项的索引
【发布时间】:2013-02-14 13:11:19
【问题描述】:

我有一个清单:

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

我想通过正则表达式获取item的索引 这就像没有正则表达式的版本:

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

【问题讨论】:

    标签: python regex list dictionary indexing


    【解决方案1】:

    如果pattern 是模式并且rethe re module

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

    您可以使用re.search instead of re.match

    enumerate 是一个方便的内置函数,可让您使用索引而不用 for i in range(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 or buffer "
    • @user1372305 很高兴它有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 2013-03-05
    • 2017-06-26
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多