在符合某个标准的字典中查找值

时间:2013-10-29 01:18:28

标签: python dictionary

如果我有一个dict如下:

d = {"1,2" : 3, "1,3" : 6, "1,4" : 5,
          "2,3" : 5, "2,4" : 6,
          "3,4" : 9,}

我正在尝试找到符合此标准的所有三胞胎:

d["a,b"] < d["a,c"] == d["b,c"]

棘手的部分是a,b和c可以被洗牌,直到满足标准。 有一种简单的方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:2)

d = {"1,2" : 3, "1,3" : 6, "1,4" : 5,
          "2,3" : 5, "2,4" : 6,
          "3,4" : 9,}
import itertools
for item in itertools.combinations(d.keys(), 3):
    if d[item[0]] < d[item[1]] == d[item[2]]:
        print d[item[0]], d[item[1]], d[item[2]]

<强>输出

5 6 6
3 6 6

使用列表理解:

import itertools
print [(d[item[0]], d[item[1]], d[item[2]])
        for item in itertools.combinations(d.keys(), 3)
        if d[item[0]] < d[item[1]] == d[item[2]]]

<强>输出

[(5, 6, 6), (3, 6, 6)]

答案 1 :(得分:2)

这应该与OP要求的相符,但可能不是他们需要的。 编辑:现在只需一个循环

d = {"1,2" : 3, "1,3" : 6, "1,4" : 5,
          "2,3" : 5, "2,4" : 6,
          "3,4" : 9,
      "a,b" : 1, "a,c" : 2, "b,c": 2
    }

parts = set(",".join(d.keys()).split(',')) # Get all parts of the keys
import itertools
for a,b,c in itertools.permutations(parts,3):
    # Get each possible permutation of a,b,c
    try:
        # Try and find an item that matches the condition
        if d[",".join([a,b])] < d[",".join([a,c])] == d[",".join([b,c])]:
            print (a,b,c)
    except KeyError:
        pass # keyerror

问题是这没有任何回报,因为没有匹配该条件的三元组。我添加了一组额外的键,以提供 输出字面('a', 'b', 'c')以显示它的工作原理。