![](/img/trans.png)
[英]How to get the index of a dictionary inside list if a specific key item is in the dictionary
[英]Get index of dictionary item in list by regexp
我有一個清單:
[
{
'avail': 'blabla',
'rep_main': 'qweqwe',
....
},
{
'avail': 'asdasd',
'rep_main': 'zxczxc',
....
},
...
]
我想通過regexp獲取項目的索引,就像沒有regexp的版本一樣:
[list['rep_main'] for elem in list].index('qweqwe')
如果pattern
是pattern而re
是re
模塊 :
[i for i, elem in enumerate(mylist) if re.match(pattern, elem['rep_main'])]
您可以使用re.search
而不是re.match
。
enumerate
是一種方便的內置函數,可讓您使用索引而不使用for i in range(len(mylist))
丑陋的for i in range(len(mylist))
。
注意:上面的表達式顯然是一個列表。 .index()
方法返回第一個匹配的索引。 為此,請編寫:
next(i for i, elem in enumerate(mylist) if re.match(pattern, elem['rep_main']))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.