给定以下 python 字典列表:
results = [[{'id': '001', 'result': [0,0,0,0,1]},
{'id': '002', 'result': [1,1,1,1,1]},
{'id': '003', 'result': [0,1,1,None,None]},
{'id': '004', 'result': [0,None,None,1,0]},
{'id': '005', 'result': [1,0,None,1,1]},
{'id': '006', 'result': [0,0,0,1,1]}],
[{'id': '001', 'result': [1,0,1,0,1]},
{'id': '002', 'result': [1,1,1,1,1]},
{'id': '003', 'result': [0,1,1,None,None]},
{'id': '004', 'result': [0,None,None,1,0]},
{'id': '005', 'result': [1,0,None,1,1]},
{'id': '006', 'result': [1,0,1,0,1]}]
]
我想根据“结果”的值生成一个新的排序列表(在 python 和 golang 中),方法是比较每个组中玩家(“id”)之间的结果,然后根据数量对它们进行排序匹配条目(无结果被丢弃且不计入):
在第一轮和第二轮中,001和006共有9个匹配答案:
001 = [0,0,0,0,1] 006 = [0,0,0,1,1] - 四个匹配的答案。
第二轮,001和006有五个匹配的答案:
001 = [1,0,1,0,1] 006 = [1,0,1,0,1] - 五个匹配的答案
sorted_results = ['001','006','002','005','003','004']
'001' 和 '006' 是列表中的前两项,因为它们具有最多的匹配结果 - 9。
最佳答案
如果您按照“相同结果的最大数量”对这些项目进行排序,这就是您得到的结果:
['003', '004', '005', '006', '001', '002']
如果您的意思是别的(即不是“相同结果的最大数量”),请澄清您的问题。此外,您可以简单地修改 max_identical
函数,使其按照您对相似的定义运行。
上面的结果是用以下方法计算的:
from collections import defaultdict
results = [{'id': '001', 'result': [0, 0, 0, 0, 1]},
{'id': '002', 'result': [1, 1, 1, 1, 1]},
{'id': '003', 'result': [0, 1, 1, None, None]},
{'id': '004', 'result': [0, None, None, 1, 0]},
{'id': '005', 'result': [1, 0, None, 1, 1]},
{'id': '006', 'result': [0, 0, 0, 1, 1]}]
def max_identical(lst):
counts = defaultdict(lambda: 0)
for x in lst:
if x is not None:
counts[x] += 1
return max(counts.values())
results = sorted(results, key=lambda x: max_identical(x['result']))
print [x['id'] for x in results]
关于python - 根据相似度最高的值对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19118968/