如果我有一个字典列表,例如:
l = [{'dist':56, 'responder':N}, {'dist':26, 'responder':N}, {'dist':86, 'responder':N}]
我想返回 2 个最小距离(“dist”)以及“responder”的值,在 Python 中最好的方法是什么?
如果我有一个字典列表,例如:
l = [{'dist':56, 'responder':N}, {'dist':26, 'responder':N}, {'dist':86, 'responder':N}]
我想返回 2 个最小距离(“dist”)以及“responder”的值,在 Python 中最好的方法是什么?
尝试先对列表进行排序
>>> 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']
使用@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}]