gpt4 book ai didi

python - 使用一对键创建值的并集

转载 作者:行者123 更新时间:2023-12-01 08:20:07 24 4
gpt4 key购买 nike

我正在研究社交媒体共同 friend 问题,我选择使用字典来代表他们。我被困在这样的部分,你需要一对用户说 a 和 b 并创建一个具有他们的 friend 列表并集的集合,例如ab -> [{b,c,d,e},{c,d,a}]

注意:下面的代码表示有一个用户,他有一些 friend ,这些 friend 存储在字典中。

现在,我想将每个用户与好友列表中的每个其他用户配对,并创建一个集合列表,其中包含两个用户的好友列表。

users = {
'a': ['b', 'c', 'd', 'e'],
'b': ['c', 'd', 'a'],
'c': ['a', 'b'],
'd': ['a','b','e'],
'e': ['a','d']
}

最佳答案

你可以将列表字典转换为集合字典,这样你就可以对 itertools.combinations 返回的两个用户的每个组合使用集合交集来找到他们共同的 friend ,并形成一个由用户对的 freezesets 索引的集合字典:

from itertools import combinations
u = {k: set(l) for k, l in users.items()}
{frozenset((a, b)): u[a] & u[b] for a, b in combinations(u, 2)}

这将返回:

{frozenset({'b', 'a'}): {'c', 'd'},
frozenset({'a', 'c'}): {'b'},
frozenset({'a', 'd'}): {'b', 'e'},
frozenset({'a', 'e'}): {'d'},
frozenset({'b', 'c'}): {'a'},
frozenset({'b', 'd'}): {'a'},
frozenset({'b', 'e'}): {'a', 'd'},
frozenset({'c', 'd'}): {'b', 'a'},
frozenset({'c', 'e'}): {'a'},
frozenset({'e', 'd'}): {'a'}}

关于python - 使用一对键创建值的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700257/

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