2017-05-30 52 views
0

我試圖找出如何讓衝突查找衝突並設置Python的

nbr_dict = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1,5}} 

我希望它看起來像

Clashes?: key1 
key1 and key2: None 
key1 and key3: 1 

Clashes?: key2 
key2 and key1: None 
key2 and key3: 5 

Clashes?: key3 
key3 and key1: 1 
key3 and key2: 5 

這裏是我的代碼的例子,我設法得到:

def main(): 
    nbr_dict = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1,5}} 
    clashes = input('Clashes?: ') 
    for key in sorted(nbr_dict): 
     if key != clashes: 
      print('{} and {}'.format(clashes, key)) 
      #I'm pretty sure all the arithmetic goes here# 

main() 

假定用戶給出的所有輸入都是有效的

+0

1.整理字典有什麼意義? 2.你將'key'與'clashes'進行比較,但是'key'在該上下文中是'int',而'clash'是key1/key2/key3 - 他們爲什麼會*相等? – alfasin

+0

回答你的問題,1:對它進行排序,如果我說我添加了一個新的鍵值'key0':{5,6}輸出將是:衝突?:key1 key1和key0:無 key1和key2:無 key1和key3:1 2.該鍵實際上是一個字符串,'key1','key2'等,還是你實際上是指這些值?不等於檢查密鑰是否與衝突相同,以便它不會輸出密鑰1和密鑰1或密鑰2和密鑰2或密鑰3和密鑰3這是否回答您的問題? –

回答

1

爲什麼不直接使用set路口,你的數據已經在集:

def main(): 
    nbr_dict = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1, 5}} 
    clashes = input('Clashes?: ') 
    if clashes in nbr_dict: 
     target = nbr_dict[clashes] 
     for k, v in nbr_dict.items(): 
      if k != clashes: 
       # for raw data: `target & v`, the rest is just to match your desired output 
       clash_values = [str(i) for i in target & v] 
       print("{} and {}: {}".format(clashes, k, ", ".join(clash_values) or None)) 
    else: 
     print("No such key: {}".format(clashes)) 

main() 

Clashes?: key1 
key1 and key3: 1 
key1 and key2: None 

Clashes?: key2 
key2 and key3: 5 
key2 and key1: None 

Clashes?: key3 
key3 and key2: 5 
key3 and key1: 1 

Clashes?: key4 
No such key: key4 

編輯:如果你需要一個有序的版本,它在很大程度上是相同的:

def main(): 
    nbr_dict = {'key1': {1, 2, 3}, 'key2': {4, 5, 6}, 'key3': {1, 5}} 
    sorted_keys = sorted(nbr_dict.keys()) # lets get a nice list of sorted keys 
    clashes = input('Clashes?: ') # user input 
    if clashes in nbr_dict: # simple validation 
     target = nbr_dict[clashes] # this is our user selected set 
     for k in sorted_keys: # lets loop through our sorted keys 
      if k != clashes: # don't compare with the user selected key 
       v = nbr_dict[k] # this is our compare set 
       # the same boilerplate from now on... 
       clash_values = [str(i) for i in target & v] 
       print("{} and {}: {}".format(clashes, k, ", ".join(clash_values) or None)) 
    else: 
     print("No such key: {}".format(clashes)) 

您可以進一步排序clash_values如果設定交叉口內的元素應打印作爲排序了。

3

您需要交集。

for key, value in nbr_dict.items(): 
    if key != clashes: 
     diff = nbr_dict[clashes] & value 
      if len(diff): 
       print (key, diff) # I leave you to figure out the formatting here 

正如在問題的評論中已經指出的那樣,您不需要對字典進行排序。但正如MSeifert指出的那樣,如果顯示順序很重要,您可能仍然需要排序。

+0

我認爲排序是在那裏,所以結果按預期/要求的順序打印。 – MSeifert

+1

好點@MSeifert更新了答案 – e4c5