Python - 计算列表中项目列表的出现次数?
Python - count the occurrences of a list of items in a list?
正在尝试计算一个列表中的值在另一个列表中出现的次数。
在以下情况下:
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})
您需要什么价值?
因为你这里的计数器实际上 returns 0 当被要求输入密钥 4:
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
无法知道您期望计算 4 秒,因此默认情况下仅考虑它在列表中找到的元素。另一种方法是:
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}
一个计数器是一个字典并实现更新方法,它保留零:
>>> 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})
正在尝试计算一个列表中的值在另一个列表中出现的次数。 在以下情况下:
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})
您需要什么价值?
因为你这里的计数器实际上 returns 0 当被要求输入密钥 4:
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
无法知道您期望计算 4 秒,因此默认情况下仅考虑它在列表中找到的元素。另一种方法是:
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}
一个计数器是一个字典并实现更新方法,它保留零:
>>> 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})