python - 在字典中查找符合特定条件的集合

标签 python dictionary lookup

我有一本字典。如果 V 在 DICT[K] 中,则 someFunc(k, v) 和 someFunc(v, k) 都返回 true(并且 K 在 DICT[V] 中)。字典可能如下所示:

{
1: [2, 3, 5],
2: [3, 1, 5],
3: [1, 2],
5: [2, 1],
}

我想在字典中找到符合此条件的所有特定长度的数字集:对于字典中的任何对,someFunc(x, y) 和 someFunc(y, x) 必须为真。例如,对于我展示的字典:

{1, 2, 3} 将是一个有效的长度为 3 的集合。标准必须有效,因为所有项目都包含所有其他项目:

  • dict[1] 包含 2, 3
  • dict[2] 包含 1, 3
  • dict[3] 包含 1, 2

如果我知道所有有效集合都必须包含给定数字,那么在给定字典中找到所有给定长度的集合的最佳方法是什么。

最佳答案

from itertools import combinations
from collections import OrderedDict

def sf(k,v,d):
    return (k in d[v]) and (v in d[k])

def lenN(d, n):
    # create a list of unique items
    l = list(OrderedDict.fromkeys(i for x in d for i in d[x]))
    # collect matching groups
    V = list()
    for C in combinations(l, n):
        for P in combinations(C, 2):
            if not sf(P[0], P[1], d): break
        else: V.append(C)
    return V

d = { 1: [2, 3, 5], 2: [3, 1, 5], 3: [1, 2], 5: [2, 1], }

print lenN(d, 3)

输出

[(2, 3, 1), (2, 5, 1)]

关于python - 在字典中查找符合特定条件的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727751/

相关文章:

python - Sklearn AffinityPropagation 内存错误

C++ 中的 Python 风格字典?

Python检查字典是否是其他字典的一部分

python - Pandas 中的字典列表

java - 如何: Locate a Resource file within a JAR file without knowing the name and location upfront

VBA 尝试将完整字符串与部分字符串匹配以查找相应的值

python - 使用 py2app 资源目录

python - 是否有可以对有限状态机进行时间逻辑模型检查的 Python 包?

python - Hadoop:检查实际运行了多少个映射器节点

c# - 在 C# 中完成查找的最快方法以及如何处理 double 值的不精确性?