试图计算一个列表中的值出现在另一个列表中的次数。 如果是
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})
答案 0 :(得分: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
答案 1 :(得分:0)
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}
答案 2 :(得分:0)
计数器是字典,并实现了update方法,该方法保留了零:
category_id