[英]Python - count the occurrences of a list of items in a list?
Trying to count how many times a value from a list appears in another list.尝试计算列表中的值出现在另一个列表中的次数。 In the case of:如果是:
my_list = [4,4,4,4,4,4,5,8]
count_items = [4,5,8]
this works fine:这工作正常:
from collections import Counter
print (Counter(my_list))
>> Counter({4: 6, 5: 1, 8: 1})
However, if my_list does not have any entries for '4', for example但是,如果 my_list 没有任何“4”条目,例如
my_list = [5,8]
count_items = [4,5,8]
print (Counter(my_list))
>> Counter({5: 1, 8: 1})
While I am looking for this output:当我在寻找这个 output 时:
>> Counter({4: 0, 5: 1, , 8: 1})
What do you need the value for?你需要什么价值?
Because the counter you have here actually returns 0 when asked for the key 4:因为当被要求输入键 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
Counter
has no way to know that you would expect 4s to be counted, so by default only accounts for elements it finds in the list. Counter
无法知道您是否期望 4 被计算在内,因此默认情况下只考虑它在列表中找到的元素。 An alternative approach would be:另一种方法是:
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}
A counter is a dict and implements the update method, which preserves zeros:计数器是一个字典并实现更新方法,该方法保留零:
>>> 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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.