如何检查字典中哪些值具有重叠键?

时间:2017-11-18 02:34:39

标签: python dictionary

我有一本字典:

{0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}

然后我接受一个引用其中一个键的输入:

flag = 0
user = input("Enter an integer for a user ID: ")
if isinstance(user, float):
    flag = 1
if user.isdigit() and int(user) >= 0 and int(user) <= (len(network)-1) and flag == 0:
    return(user)
else:
    while user.isdigit() == False or int(user) < 0 or int(user) > (len(network)-1):
        user = input("Enter an integer for a user ID: ")

所以现在我需要帮助理解找到具有重叠键的值,例如,如果用户选择4将输出代码:

"For user with ID 4 we recommend the user with ID 2"
"That is because users 4 and 2 have 3 common friends and user 4 does not have more common friends with anyone else."

用户也无法相互了解。因此,尽管4与0有更多共同点,但他们彼此了解,因此无法工作。

谢谢!

2 个答案:

答案 0 :(得分:2)

方法:

  1. 接受matchMaker(id, d)id
  2. 的函数d
  3. d
  4. 中循环键值对
  5. 检查密钥是否与id
  6. 不同
  7. 检查身份证是否彼此了解
  8. 找到id和其他id之间的共同朋友;附加到列表l2
  9. 如果匹配,则查找全部并返回列表matches else []
  10. 代码

    d={0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}
    
    def matchMaker(id, d):
        l2=[]
        for k,v in d.items():
            if k!=id:
                if id not in v:
                    f = set(d[id]).intersection(v)
                    l2.append([len(f), k])        # append f if you want the suggestions
        matches=[]
        if l2:
            match_count = max(l2)[0]
            matchid = max(l2)[1]
            matches = [matchid]
    
            for item in l2:
                if item[1] not in matches:
                    if match_count == item[0]:
                        matches.append(item[1])
        return matches
    
    id=5
    all_matches = matchMaker(id,d)
    
    print(all_matches)
    

    要获取id的整数值,请使用all_matches[0]all_matches[1]等。

    输出

    # matches for id = 5
    [3, 1, 2]
    
    # matches for id = 4
    [2]
    

答案 1 :(得分:1)

最简单的方法是将朋友列表转换为集合。您可以使用像这样的词典理解

来做到这一点
d  = {0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}
ds = {k:set(v) for k, v in d.items()}

现在你可以通过交叉

找到共享的朋友,比如2和4
ds[2] & ds[4]

-> {0, 8, 6}

您可以使用len

计算它们
len(ds[2] & ds[4])

最后,你可以创建一个循环来找到最佳匹配(a是输入,b是输出):

def best_match_for(a):
    b = None
    af = ds[a]
    best = -1
    for k, v in ds.items():
        if k!=a and not k in af:
            ovlp = len(af & v)
            if ovlp > best:
                best = ovlp
                b = k
    return b, best if best > 0 else None