繁体   English   中英

如何计算列表中的项目出现次数,如果它不在列表中,则返回零计数?

[英]How to count item occurences in a list and return a count of zero if it is not in the list?

我有一个主列表,我们命名为 m_list:

m_list = ['red','orange','yellow','green','blue','indigo','violet']

我想计算 m_list 中的项目在另一个列表中出现的频率,我们称之为 e_list:

e_list = ['red','red','red','violet','blue','blue']

所需的 output 将是一个字典,其中m_list中 m_list 中每个项目的计数,如果项目不在e_list中则e_list

像这样的东西:

{'red':3,'orange':0,'yellow':0,'green':0,'blue':2,'indigo':0,'violet':1}

另一种方法是使用collection模块中的Counter class。

>>> from collections import Counter

>>> m_list = ['red','orange','yellow','green','blue','indigo','violet']
>>> e_list = ['red','red','red','violet','blue','blue']

>>> counts = Counter(e_list)          # Count the number of times each entry of e_list appears
>>> for key in m_list:
...     counts.setdefault(key, 0)     # Add other entries of m_list to the counter with a value of 0.
>>> print(counts)
Counter({'red': 3, 'blue': 2, 'violet': 1, 'orange': 0, 'yellow': 0, 'green': 0, 'indigo': 0})

Counter class 的作用就像一个dict ,因此您可以获得所需的所有功能,以及一些漂亮的方法,如.most_common()

一个非常基本的实现可能如下所示:

m_list = ['red','orange','yellow','green','blue','indigo','violet']
e_list = ['red','red','red','violet','blue','blue']

result = {}
for key in m_list:
    result[key] = e_list.count(key)

result将与您想要的完全一样。 请记住,对于较长的列表,这绝对不是一个有效的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM