簡體   English   中英

對Python中的dict進行分組和排序

[英]Groupby and sort the values in dict in Python

我在python中有一個字典,如下所示,我必須按“標簽”分組,並為每個“標簽”獲得最高的“信心”值

[{'label': 'id',
  'confidence': 0.11110526,
  'topleft': {'x': 0, 'y': 0},
  'bottomright': {'x': 187, 'y': 57}},

{'label': 'id',
  'confidence': 0.10690566,
  'topleft': {'x': 265, 'y': 0},
  'bottomright': {'x': 525, 'y': 54}},

 {'label': 'name',
  'confidence': 0.15541315,
  'topleft': {'x': 9, 'y': 24},
  'bottomright': {'x': 116, 'y': 58}},

 {'label': 'group',
  'confidence': 0.12578075,
  'topleft': {'x': 53, 'y': 24},
  'bottomright': {'x': 153, 'y': 61}},

 {'label': 'name',
  'confidence': 0.12709439,
  'topleft': {'x': 0, 'y': 0},
  'bottomright': {'x': 247, 'y': 84}},

 {'label': 'group',
  'confidence': 0.116156094,
  'topleft': {'x': 96, 'y': 23},
  'bottomright': {'x': 191, 'y': 61}}]    

我如何有效地做到這一點

您可以使用groupby做到這一點

for n,g in groupby(tst,key=lambda x:x['label']):
     print n,max(list(g),key=lambda x:x['confidence']).get('confidence')

結果:

id 0.11110526
name 0.15541315
group 0.12578075
name 0.12709439
group 0.116156094

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM