python - 根据相似度最高的值对字典列表进行排序

标签 python sorting go

给定以下 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/

相关文章:

algorithm - 对图书馆中几乎已排序的书籍进行排序的最佳算法是什么

ssh - Go 中的 SCP 客户端

python - 日期时间:从自身中减去日期得到 3288 天

python - 无法从 Trac 获取数据库连接?

python - 在 Python 2.7 中设置列​​表对象的属性

c++排序跟踪索引

python - 我无法让 urwid 教程示例正常工作

regex - R 根据子字符串对字符串进行排序

go - 如何解析格式为/id/123 而不是 ?foo=bar 的 URL

go - ElasticSearch 上特定搜索类型的分页