基于di

2024-06-24 12:34:19 发布

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

基于相似的值对字典进行分组很容易,但是我很难想到一种相反的好方法:对其中一个键的值与其他键的值不同的字典进行分组。你知道吗

举个例子:

a = {1: 'a', 2: 'b', 3:'c'}
b = {1: 'a', 2: 'b', 3:'d'}
c = {1: 'c', 2: 'b', 3:'d'}

这些可以分为两组,其中一个键值不同:

# Expected output:
{3: {a, b},    # Differs on 3
 1: {b, c}}    # Differs on 1

我很难想出一个好的方法来实现这样的功能。你对如何前进有什么建议吗?你知道吗


Tags: 方法功能output字典on建议例子键值
1条回答
网友
1楼 · 发布于 2024-06-24 12:34:19

假设键和值是可散列的,通过在项上使用集合可以得到字典差异。然后,您可以得到一个成对的dict列表,以及它们的区别:

a = {1: 'a', 2: 'b', 3:'c'}
b = {1: 'a', 2: 'b', 3:'d'}
c = {1: 'c', 2: 'b', 3:'d'}

def diff_dict(dicta, dictb):
    aset = set(dicta.items())
    bset = set(dictb.items())
    diff = aset ^ bset
    return tuple(set(x[0] for x in diff))

print diff_dict(a, b)
(3,)

all_dicts = [a,b,c]

listgroup = []

for dicta, dictb in itertools.combinations(all_dicts, 2):
     key = diff_dict(dicta, dictb)
     listgroup.append((key, (dicta, dictb)))

如果您只需要单个项,请使用if len(key) == 1来设置附加项的门。你知道吗

相关问题 更多 >