0

我想将 Python 字典与其自身进行比较。例如:

for key1 in d:
    for key2 in d:
        if key1 == key2:
            continue
        compare(d[key1],d[key2])

除了我将 key1 与 key 2 进行比较,然后再将其相反(key2 与 key1)进行比较,上述方法将起作用。第二个for循环的范围应该真正在key1之后开始,以避免重复比较。怎么可能呢?

4

4 回答 4

3

我认为这itertools.combinations在这里会有所帮助

>>> import itertools
>>> d = dict.fromkeys(range(5),0)
>>> list(itertools.combinations(d,2))
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

所以,对于你的情况,你想要:

for key1,key2 in itertools.combinations(d,2):
    compare(d[key1],d[key2])

这是一个愚蠢的例子,我构建了一个棕色眼睛(或者我想是头发......)的人的列表:

>>> d = dict.fromkeys(["Jon","Jane","Bob","Jim","Janice"],"blue")
>>> d["Jim"] = "Brown"
>>> d["Jane"] = "Brown"
>>> d["Bob"] = "Brown"
>>> [ (x,y) for (x,y) in itertools.combinations(d,2) if d[x]=="Brown" and d[y]=="Brown" ]
[('Jane', 'Bob'), ('Jane', 'Jim'), ('Bob', 'Jim')]
于 2013-01-15T19:31:18.133 回答
1

实际上你不需要钥匙来尊重字典。正如@mgilson 所建议的,您可以使用 itertools.combinations 直接比较字典的值

>>> from itertools import combinations
>>> d = {random.randint(1,100):i for i in range(10)}
>>> list(combinations(d.values(), 2))
[(7, 4), (7, 2), (7, 3), (7, 1), (7, 0), (7, 8), (7, 9), (7, 5), (7, 6), (4, 2), (4, 3), (4, 1), (4, 0), (4, 8), (4, 9), (4, 5), (4, 6), (2, 3), (2, 1), (2, 0), (2, 8), (2, 9), (2, 5), (2, 6), (3, 1), (3, 0), (3, 8), (3, 9), (3, 5), (3, 6), (1, 0), (1, 8), (1, 9), (1, 5), (1, 6), (0, 8), (0, 9), (0, 5), (0, 6), (8, 9), (8, 5), (8, 6), (9, 5), (9, 6), (5, 6)]
>>> 
于 2013-01-15T19:55:43.100 回答
1

使用itertools.combinations显然是最好的答案。但即使是问题的原始代码也只需要稍作修改即可完成预期的工作:

for key1 in d:
    for key2 in d:
        if key1 < key2:
            compare(d[key1],d[key2])
于 2016-11-30T12:16:02.457 回答
0

如果您想坚持使用嵌套的 for 循环,那么以下方法可以解决问题:

d = dict(a=1,b=2,c=3,d=4)
k = d.keys()
l = len(k)

for i in range(l):
    for j in range(i+1,l):
        print d[k[i]] == d[k[j]]
于 2013-01-15T20:05:23.917 回答