簡體   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