如何从列表中删除重复项并从中取出最大的

2021-10-17 13:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是python中的dict列表

[{'JP': ['Server2', 'Server1', 'Server3']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server1']}, {'JP': ['Server1']}, {'JP': ['Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}]

我想从这些文件中删除重复文件,然后取出最大值列表。在上述情况下,我的输出将是

[{'JP': ['Server2', 'Server1', 'Server3']}]

我正在尝试删除重复项。你知道吗

result = [dict(t) for t in set([tuple(d.items()) for d in result])]

它给了我一个错误unhashable type: 'list'。有指向正确方向的指针吗?你知道吗

2条回答
网友
1楼 ·

我在假设你的字典

x = [{'JP': ['Server2', 'Server1', 'Server3']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server1']}, {'JP': ['Server1']}, {'JP': ['Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}, {'JP': ['Server2', 'Server1']}]

x.sort(key = lambda x:len(x['JP']))

那么

x[-1]就是你想要的。你知道吗

更新: 借用Marco Bonelli下面的答案,您不必对数组进行实际排序。你可以简单地找到像这样的“最大的”。你知道吗

 max(x, key = lambda x:len(x['JP']))
网友
2楼 ·

这个怎么样?易于查看其工作原理易于修改:)

data = [{'JP': ['Server2', 'Server1', 'Server3']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server1']},
        {'JP': ['Server1']},
        {'JP': ['Server1']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server2', 'Server1']},
        {'JP': ['Server2', 'Server1']}]

result = dict()
for dict_ in data:
    for key, values in dict_.iteritems():
        if len(values) > len(result.get(key, [])):
            result[key] = values

相关问题