Python 统计列表中的事件

Python 统计列表中的事件,python,python-2.7,Python,Python 2.7,我正在将数字从一个文本文件加载到一个列表中,在这方面,一切正常!但现在我需要知道列表中每个数字出现了多少次。下面是我通过搜索这个网站拼凑起来的整个程序 row = [] textfile = open('take5_3.txt', 'r') yourResult = [line.split('-') for line in textfile] row.append(yourResult) print (yourResult) 任何时候,当我放置某种假定要计算结果的行时,我都

我正在将数字从一个文本文件加载到一个列表中,在这方面,一切正常!但现在我需要知道列表中每个数字出现了多少次。下面是我通过搜索这个网站拼凑起来的整个程序

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})

什么?它不清楚你要的是什么,并且对计算东西都很有用。对于长字符串/列表上的小字母表,重复调用内置的
count
方法速度惊人。