【问题标题】:Get matches between list and dictionary获取列表和字典之间的匹配项
【发布时间】:2017-11-18 20:51:56
【问题描述】:

我有一个列表和一本字典:
列表 = ['a', 'b', 'c'] 。 dict = {'1': ['a', 'd', 'e'], '2': ['b', 'c', 'f'], '3': ['b', 'a ', 'e']} 。

我想获取与列表项最匹配的密钥。如果有两个相同数量的我想要两个。

【问题讨论】:

    标签: list dictionary compare multiple-matches


    【解决方案1】:

    假设您使用 python 编写,这是一种简单的方法,它可以附加或添加新键,其值与列表的相似度最大。

    l= ['a', 'b', 'c']
    d = {'1': ['a', 'd', 'e'], '2': ['b', 'c', 'f'], '3': ['b', 'a', 'e']}
    
    high = -1
    key = []
    for k,v in d.items():
        occ = (len(l) + len(v)) - len(set(l + v))
        print((set(l+v)))
        if(occ >= high):
            if(occ == high):
                key.append(k)
            else:
                key = [k]
            high = occ
    print(key)
    

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 2020-03-31
      • 2023-01-20
      • 2019-09-22
      • 2011-09-24
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      相关资源
      最近更新 更多