【问题标题】:Python - count the occurrences of a list of items in a list?Python - 计算列表中项目列表的出现次数?
【发布时间】:2019-10-29 16:49:28
【问题描述】:

试图计算一个列表中的值出现在另一个列表中的次数。 在这种情况下:

my_list = [4,4,4,4,4,4,5,8]
count_items = [4,5,8]

这很好用:

from collections import Counter
print (Counter(my_list))
>> Counter({4: 6, 5: 1, 8: 1})

但是,如果 my_list 没有任何 '4' 的条目,例如

my_list = [5,8] 
count_items = [4,5,8]
print (Counter(my_list))
>> Counter({5: 1, 8: 1})

当我在寻找这个输出时:

>> Counter({4: 0, 5: 1, , 8: 1})

【问题讨论】:

  • 值得注意的是,尝试访问 Counter 中不存在的密钥将为该项目返回 0。所以在这种情况下,Counter(my_list)[4] 无论如何都会返回0

标签: python list counter


【解决方案1】:

你需要什么价值?

因为当被要求输入键 4 时,此处的计数器实际上返回 0:

my_list = [5,8] 
count_items = [4,5,8]
counter = Counter(my_list)
print(counter)
>> Counter({5: 1, 8: 1})
print(counter[4])
>> 0

【讨论】:

  • 您可以使用这个事实来生成所需的输出:{k: Counter(my_list)[k] for k in set(count_items)}
【解决方案2】:

Counter 无法知道您会期望 4s 被计算在内,因此默认情况下只考虑它在列表中找到的元素。另一种方法是:

my_list = [5,8]
count_items = [4,5,8]
counter = {i: sum(map(lambda x: 1 if x == i else 0, my_list)) for i in count_items}
print (counter)
>> {4: 0, 5: 1, 8: 1}

【讨论】:

    【解决方案3】:

    一个计数器是一个 dict并实现了更新方法,它保留了零:

    >>> counter = Counter(my_list)
    >>> counter
    Counter({5: 1, 8: 1})
    >>> counter.update(dict.fromkeys(count_items, 0))
    >>> counter
    Counter({5: 1, 8: 1, 4: 0})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2022-12-04
      相关资源
      最近更新 更多