在 Python 中查詢列表中給定元素的頻率之和


給定列表中包含許多重複項。我們感興趣的是找出列表中某些重複項的頻率之和。以下是我們如何實現這一點的方法。

使用 sum 函式

我們有兩個列表。一個包含值的列表,另一個包含需要從第一個列表中檢查頻率的值。因此,我們建立一個 for 迴圈來計算第二個列表中的元素在第一個列表中出現的次數,然後應用 sum 函式來獲取最終的頻率總和。

示例

 線上演示

chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']

# Apply sum
res = sum(big_list.count(elem) for elem in chk_list)

# Printing output
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)

輸出

執行以上程式碼,得到以下結果:

Given list to be analysed:
['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
Given list to with values to be analysed:
['Mon', 'Tue']
Sum of the frequency: 5

使用 collections.Counter

collections 模組中的 Counter 函式可以透過將其應用於需要分析值的列表並在遍歷僅包含需要確定頻率的元素的較小列表時,獲得所需的結果。

示例

 線上演示

from collections import Counter

chk_list= ['Mon', 'Tue']
big_list = ['Mon','Tue', 'Wed', 'Mon','Mon','Tue']

# Apply Counter

res = sum(Counter(big_list)[x] for x in chk_list)

# Printing output
print("Given list to be analysed: \n", big_list)
print("Given list to with values to be analysed:\n", chk_list)
print("Sum of the frequency: ", res)

輸出

執行以上程式碼,得到以下結果:

Given list to be analysed:
['Mon', 'Tue', 'Wed', 'Mon', 'Mon', 'Tue']
Given list to with values to be analysed:
['Mon', 'Tue']
Sum of the frequency: 5

更新於: 2020年5月5日

428 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告