通过迭代字典查找缺少的元素

时间:2018-07-10 17:28:38

标签: python python-3.x algorithm

我正在尝试查找缺少的元素,但我一直遇到问题 下面是我的代码。看来它没有遍历字典

def finder(arr1,arr2):
    if len(arr1) == len(arr2):
        return 

    target = {}
    for k in arr1:
        if k in target:
            target[k] +=1
        else:
            target[k] = 1
    print (target)
    for k in arr2:
        if k in target:
            target[k] -= 1
        else:
            target[k] = 1
    print (target)

    for k,v in target.items():
        if v != 0
            print(k ,"is the missing number")

#         else:
#            return 

1 个答案:

答案 0 :(得分:0)

如果您有两个字典(按定义不能有重复的键)

def finder(first_dict, second_dict):
    return set(first_dict) - set(second_dict)

或者,如果您的列表中包含可能重复的元素:

def finder(first_list, second_list):
    return (collections.Counter(first_list) - collections.Counter(second_list)).keys()