1

我一直试图在列表中找到最大的结果 - 使用置信度值。

列表示例:

[[{u'categories': [u'health-beauty'], u'confidence': 0.3333333333333333},
 {u'categories': [u'activities-events'], u'confidence': 0.6666666666666666}]]

将返回活动事件字典

[[{u'categories': [u'home-garden'], u'confidence': 0.3333333333333333},
 {u'categories': [u'None of These'], u'confidence': 0.3333333333333333},
 {u'categories': [u'toys-kids-baby'], u'confidence': 0.3333333333333333}]]

将返回所有三个,因为它们是相等的

[[{u'categories': [u'entertainment'], u'confidence': 1.0}]]

会回归娱乐

我试图利用 python 的 max 函数:

seq = [x['confidence'] for x in d[0]]
max(seq)

但这只是返回值

4

4 回答 4

2

您可以在自己的示例中找到最大置信度,然后使用它filter来创建所有最大记录的列表:

max_conf = max(x['confidence'] for x in d[0])
filter(lambda x: x['confidence']==max_conf, d[0])

如以下评论中所述,filter可以用列表理解替换:

max_records = [x for x in d[0] if x['confidence'] == max_conf]
于 2012-11-12T08:47:37.073 回答
0
max(d[0], key=lambda x: x['confidence'])

d[0]返回具有最高confidence属性的整个元素。

其他方式:

import operator as op

max(d[0], key=op.attrgetter('confidence'))
于 2012-11-12T08:28:45.937 回答
0
sorted(d[0], key=lambda k: k['confidence'])[-1]

只是另一种方法。d[0]还返回具有最高confidence属性的整个元素。

于 2012-11-12T08:42:51.107 回答
0

如果您想以最高的置信度检索所有匹配项,max则不是选项。您首先需要按 key = confidence 对其进行排序(您可以为此目的使用sorted ,并使用operator.itemgetter来检索密钥),然后根据置信度对元素进行分组(您可以使用itertools.groupby )。最终归还信心最高的群体

from itertools import groupby
from operator import itemgetter
groups = groupby(sorted(inlist[0], key = itemgetter(u'confidence'), reverse = True),
                 key = itemgetter(u'confidence'))
[e[u'categories'] for e in next(groups)[-1]]

例子

>>> inlist = [[{u'categories': [u'health-beauty'], u'confidence': 0.3333333333333333}, {u'categories': [u'activities-events'], u'confidence': 0.6666666666666666}]]
>>> groups = groupby(sorted(inlist[0], key = operator.itemgetter(u'confidence'), reverse = True),key = operator.itemgetter(u'confidence'))
>>> [e[u'categories'] for e in next(groups)[-1]]
[[u'activities-events']]
>>> inlist = [[{u'categories': [u'home-garden'], u'confidence': 0.3333333333333333}, {u'categories': [u'None of These'], u'confidence': 0.3333333333333333}, {u'categories': [u'toys-kids-baby'], u'confidence': 0.3333333333333333}]]
>>> groups = groupby(sorted(inlist[0], key = operator.itemgetter(u'confidence'), reverse = True),key = operator.itemgetter(u'confidence'))
>>> [e[u'categories'] for e in next(groups)[-1]]
[[u'home-garden'], [u'None of These'], [u'toys-kids-baby']]
>>> inlist = [[{u'categories': [u'entertainment'], u'confidence': 1.0}]]
>>> groups = groupby(sorted(inlist[0], key = operator.itemgetter(u'confidence'), reverse = True),key = operator.itemgetter(u'confidence'))
>>> [e[u'categories'] for e in next(groups)[-1]]
[[u'entertainment']]
>>> 
于 2012-11-12T08:55:28.783 回答