python - 从字典中返回一组具有共同值的键对

标签 python python-3.x function dictionary set

如何编写一个函数,它需要一个字典并返回一组由至少具有一个公共(public)值的键对组成的集合?

示例:

我有以下字典:

dict = {
'C': {'123'}, 
'A': {'123', '456'}, 
'D': {'123'}, 
'B': {'789', '456'}, 
'E': {'789'}}

MyFunction(dict) 应该返回我:

{("A", "B"), ("A", "C"), ("A", "D"), ("B", "E"), ("C", "D")}

最佳答案

使用itertools.combinations:

from itertools import combinations

d = {
    'C': {'123'}, 
    'A': {'123', '456'}, 
    'D': {'123'}, 
    'B': {'789', '456'}, 
    'E': {'789'}
}

def MyFunction(d):
    out = set()
    for i, j in combinations(d, 2):
        if d[j].intersection(d[i]) and (i, j) not in out and (j, i) not in out:
            out.add((i, j))
    return set(tuple(sorted(i)) for i in out)

print(MyFunction(d))
print(MyFunction(d) == {("A", "B"), ("A", "C"), ("A", "D"), ("B", "E"), ("C", "D")})

输出是:

{('A', 'D'), ('A', 'B'), ('B', 'E'), ('A', 'C'), ('C', 'D')}
True

如果您认为 ('A', 'C')('C', 'A') 相同,则可以替换

return set(tuple(sorted(i)) for i in out)

仅仅

return out

关于python - 从字典中返回一组具有共同值的键对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53420730/

相关文章:

Python OpenCV2(cv2)包装器获取图像大小?

python - 将列添加到数据框并预定义重复行

python - 导入单个函数

c - 当我使用条件运算符或不带 return 语句的 if 语句时,函数返回正确的值

python - Matplotlib Graphs下的渐变填充

python - 解析 Python 3.x 中的转义字符

css - 单击按钮以使用 Selenium 加载其他元素后加载完整的 HTML

c++ - 从函数发出返回值

Python:在一组数字中寻找趋势

python - 在整数中添加浮点值时获取不同的值(PYTHON)