简体   繁体   English

计算列表中的出现次数

[英]Counting occurrences within list

I am loading numbers from a text file into a list, and in that regard, everything works fine! 我正在将文本文件中的数字加载到列表中,在这方面,一切正常! But now I need to know how many times each number occured in the list. 但现在我需要知道列表中每个号码出现的次数。 Below is my whole program that I have pieced together by searching this site. 下面是我通过搜索这个网站拼凑的整个程序。

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

Any time I put some sort of line that is suppose to count my result, I get one because it is only counting the list and not the items within the list. 每当我设置一些假定计算结果的行时,我得到一行因为它只计算列表而不是列表中的项目。

As Joran has commentted, your question is really not clear. 正如Joran所评论的那样,你的问题真的不明确。 I will try to fill in the blank here. 我会尽力填补这里的空白。

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)

And here is the output 这是输出

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

You'll need to make a dictionary with the number as the key and the count of the number as the value. 您需要创建一个字典,其中数字作为键,数字的计数作为值。 just keep incrementing the value as you go along. 随着你继续增加价值。

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

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