gpt4 book ai didi

2个列表之间的Python区别

转载 作者:行者123 更新时间:2023-12-02 16:22:33 24 4
gpt4 key购买 nike

我找到了很多例子,但没有一个有重复项。

我有 2 个字典列表:

d1 = [{"id": 1, "value": 2}, {"id": 1, "value": 2}]
d2 = [{"id": 1, "value": 2}, {"id": 4, "value": 4}]

我想实现的是:

d1-d2
[{"id": 1, "value": 2}]

d2-d1
[{"id": 4, "value": 4}]

diff(d1, d2)
[{"id": 1, "value": 2}, {"id": 4, "value": 4}]

最佳答案

假设您的值,而不仅仅是键,在每个字典中都是可哈希的,您可以使 frozenset每个dict s .items() , 将它们收集到 a collections.Counter ,并对 Counter 执行类似异或的运算获取不同的计数。然后你就把 Counter 弄平了再次,并转换 frozenset回到dict小号:

from collections import Counter

def diff(l1, l2):
c1 = Counter(frozenset(d.items()) for d in l1)
c2 = Counter(frozenset(d.items()) for d in l2)
c1xc2 = (c1 - c2) + (c2 - c1) # Equivalent to c1 ^ c2 if they were sets, but we need counts, and Counter doesn't support ^
# elements() flattens the Counter to iterable of repeated values, map(dict, ...)
# converts frozensets back to dicts
return list(map(dict, c1xc2.elements()))

更简单的计算操作d1 - d2d2 - d1留作练习;所有情况下的关键是转换您的 listdict s 至 Counterfrozenset dict 的小号的 .items() ,使用 - 执行您关心的操作, 然后转换回 listdict

这应该相当有效(在组合输入大小上大约为 O(n));对其进行改进将需要更多的自定义代码,坦率地说,这是不值得的。

关于2个列表之间的Python区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65227278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com