如果我有一个像:
这样的词组列表l = [{'dist':56, 'responder':N}, {'dist':26, 'responder':N}, {'dist':86, 'responder':N}]
我希望返回2个最小距离('dist')以及'responder'的值,在Python中这样做的最佳方法是什么?
答案 0 :(得分:2)
首先尝试对列表进行排序
>>> from operator import itemgetter
>>> sorted(l, key=itemgetter('dist'), reverse=True)
[{'responder': 'N', 'dist': 86}, {'responder': 'N', 'dist': 56}, {'responder': 'N', 'dist': 26}]
然后切前两个元素
>>> sorted(l, key=itemgetter('dist'), reverse=True)[:2]
[{'responder': 'N', 'dist': 86}, {'responder': 'N', 'dist': 56}]
并从他们那里获得响应者
>>> map(itemgetter('responder'), sorted(l, key=itemgetter('dist'), reverse=True)[:2])
['N', 'N']
答案 1 :(得分:1)
使用@ Bakuriu的解决方案进行修改:
l = [{'dist':56, 'responder':'n'}, {'dist':26, 'responder':'n'}, \
{'dist':86, 'responder':'n'}]
smallestTwo = sorted(l, key=lambda d: d['dist'])[:2]
输出:
[{'responder': 'n', 'dist': 26}, {'responder': 'n', 'dist': 56}]