繁体   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