簡體   English   中英

計算列表中的出現次數

[英]Counting occurrences within list

我正在將文本文件中的數字加載到列表中,在這方面,一切正常! 但現在我需要知道列表中每個號碼出現的次數。 下面是我通過搜索這個網站拼湊的整個程序。

row = []  
textfile = open('take5_3.txt', 'r')
yourResult = [line.split('-') for line in textfile]
row.append(yourResult)    
print (yourResult)    

每當我設置一些假定計算結果的行時,我得到一行因為它只計算列表而不是列表中的項目。

正如Joran所評論的那樣,你的問題真的不明確。 我會盡力填補這里的空白。

textfile = open('take5_3.txt', 'r')
yourResult = [line.split('-') for line in textfile.readlines()] # use readline to read from the file
# You probably need to flatten the content in yourResult.
# Assume now yourResult is something like this ['a', 'a', 'bdbd', 'bbc', 'bbc']
# you can use Counter to do the counting
from collections import Counter
print Counter(yourResult)

這是輸出

Counter({'a': 2, 'bbc': 2, 'bdbd': 1})

您需要創建一個字典,其中數字作為鍵,數字的計數作為值。 隨着你繼續增加價值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM