簡體   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