2016-03-26 118 views
0

我正在嘗試編寫一個將字典中的每個值與每個其他值進行比較的python代碼。例如:將字典中的每個值與其他值進行比較

dict={key1:[values1],key2:[values2],key3:[values3}. 

我想比較每個值與每個其他值。即value1value2,value1value3,value2value3

回答

1

這是你想要的?

for k in topology: 
    for j in topology: 
     if k == j: 
      continue 
     else: 
      # compare values at key k and key j 
      my_compare_function(topology[k], topology[j]) 
+0

是的,謝謝。有效 –

0

您可以使用itertools.combinations創建所有對。下面是一個簡單的例子:

from itertools import combinations 
# create an example dictionary 
dict = {"a": 1, "b": 2, "c": 2} 
# generate all pairs 
all_pairs = list(combinations(dict.items(), r = 2)) 
# create mapping of comparisons of the values of each pair 
{pair:pair[0][1] == pair[1][1] for pair in all_pairs} 

輸出:

(('c', 2), ('b', 2)): True, (('a', 1), ('b', 2)): False, (('a', 1), ('c', 2)): False} 
相關問題