【问题标题】:compare a list with values in dictionary将列表与字典中的值进行比较
【发布时间】:2019-03-24 13:46:21
【问题描述】:

我有一本包含值列表和列表的字典:

dict1={'first':['hi','nice'], 'second':['night','moon']}
list1= [ 'nice','moon','hi']

我想将字典中的值与 list1 进行比较,如果每个键的值出现在列表中,则为键创建一个计数器: 输出应该是这样的:

   first 2
   second 1

这是我的代码:

count = 0 
for list_item in list1: 
    for dict_v in dict1.values():
      if list_item.split() == dict_v:
        count+= 1
        print(dict.keys,count)

有什么帮助吗?提前致谢

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    您可以使用以下字典理解:

    {k: sum(1 for i in l if i in list1) for k, l in dict1.items()}
    

    鉴于您的示例输入,这将返回:

    {'first': 2, 'second': 1}
    

    【讨论】:

      【解决方案2】:

      您可以使用集合获取列表和dict1 的值的交集:

      for key in dict1.keys():
          count = len(set(dict1[key]) & set(list1))
          print("{0}: {1}".format(key,count))
      

      【讨论】:

      • 请注意,在 for 循环的每次迭代中一次又一次地从 list1 创建集合有点多余。我会在循环之前移动它。
      • 另外,要迭代 key 和 value,你应该迭代 dict.items,它更清晰,更惯用。另外,请考虑 3.6+ 中的 f 字符串,而不是 str.format
      【解决方案3】:

      我会从list1 中创建一个set 用于O(1) 查找时间并访问intersection 方法。然后使用 dict 理解。

      >>> dict1={'first':['hi','nice'], 'second':['night','moon']}
      >>> list1= [ 'nice','moon','hi']
      >>> 
      >>> set1 = set(list1)
      >>> {k:len(set1.intersection(v)) for k, v in dict1.items()}
      {'first': 2, 'second': 1}
      

      intersection 接受任何可迭代的参数,因此不需要从 dict1 的值创建集合。

      【讨论】:

      • 我觉得这很棒!可能会很好添加一种药水来打印 OP 所需的输出。
      【解决方案4】:

      虽然简洁可以很好,但我认为最好也提供一个尽可能接近 OP 原始代码的示例:

      # notice conversion to set for O(1) lookup 
      # instead of O(n) lookup where n is the size of the list of desired items
      
      dict1={'first':['hi','nice'], 'second':['night','moon']}
      set1= set([ 'nice','moon','hi']) 
      
      for key, values in dict1.items():
          counter = 0
          for val in values: 
              if val in set1:
                  counter += 1
          print key, counter
      

      【讨论】:

        【解决方案5】:

        最简单和最基本的方法是:

        dict1={'first':['hi','nice'], 'second':['night','moon']}
        list1= [ 'nice','moon','hi']
        listkeys=list(dict1.keys())
        listvalues=list(dict1.values())
        for i in range(0,len(listvalues)):
            ctr=0
            for j in range(0,len(listvalues[i])):
                for k in range(0,len(list1)):
                    if list1[k]==listvalues[i][j]:
                        ctr+=1
            print(listkeys[i],ctr)
        

        希望对你有帮助。

        【讨论】:

          【解决方案6】:

          使用collections.Counter

          from collections import Counter
          
          c = Counter(k for k in dict1 for i in list1 if i in dict1[k])
          # Counter({'first': 2, 'second': 1})
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-06-21
            相关资源
            最近更新 更多