2017-05-30 54 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