繁体   English   中英

如何删除列表中的字典元素?

[英]How can I remove an dictionary element in list?

列表中有一些字典:

a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]

这本字典的所有键和值都是int类型,有些字典有相同的键,我想保留那些具有相同键且值比其他字典大的字典,我该怎么做? 示例:我想获取此列表:

[{1: 3}, {2: 5}]

假设每个字典只有一个键/值对,这里有一个可能的解决方案。 本质上,创建一个新字典来跟踪每个键的最大值。 然后,将其变成最终列表。

def remove_duplicates(dicts):
    merged = {}
    for d in dicts:
        key, value = list(d.items())[0]
        if key not in merged:
            merged[key] = value
        else:
            merged[key] = max(
                merged[key], value
            )
    return [
        {key: value}
        for key, value in merged.items()
    ]
a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]

output = {}

for d in a:
    k = list(d.keys())[0]
    v = list(d.values())[0]
    if k not in output.keys():
        output[k] = v
    else:
        if output[k] < v:
            output[k] = v

output = [{k:v} for k, v in output.items()]

print(output)
from itertools import groupby
a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]
[{k, max(y[1] for y in g)} # build up the result by recreating the list of maps by taking the keys in the group and map them to the biggest value in the group
 for k, g
 in groupby((sorted( # group everything together, so that those touples with the same key (=index 0) are in the same group
     ((k, v) for m in a for k, v in m.items())  # transform the list of maps to a generator of tuples
     , key=lambda x: x[0])), key=lambda x: x[0])]

所以在这里我首先将映射列表转换为元组列表(这更有意义,但这只是我),通过键将它们组合在一起,然后通过取其中的最大值为每个键创建新映射每组。

BrownieInMotion 的方法相同的逻辑,但代码更清晰,使用列表理解来获得结果。

a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]

temp = {}
for item in a:
    i, v = list(*item.items())

    if i not in temp:
        temp[i] = v
    else:
        temp[i] = max(v, temp[i])

print([{i: v} for i, v in temp.items()])

解包用法list(*item.items())仅限于单键字典。 如果你想取消限制,你可以继续使用list(item.items())[0]

使用collections.defaultdict简单方法:

from collections import defaultdict

a = [{1: 2}, {1: 3}, {2: 5}, {2: 3}]

temp = defaultdict(lambda: float("-inf"))
for item in a:
    [(i, v)] = item.items()
    temp[i] = max(v, temp[i])

res = [{i: v} for i, v in temp.items()]
print(res)

输出

[{1: 3}, {2: 5}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM