可能重复: How to calculate the occurrences of a list item in Python?
我正在做一项民意调查。为此,我正在使用Python,而我所坚持的部分是试图弄清楚如何计算某件事情出现的次数,比如"General Store“出现的次数。
例如民意测验:
你在哪里看到的广告最多?
如果需要该信息,则通过单选按钮提交投票数据。所有这些答案都会附加到列表中,然后我想要创建一个结果页面,显示每件事情被投票的次数。
发布于 2012-08-02 15:07:38
首先,我要说的是,你可能对你的投票结果问题使用了错误的解决办法。为什么不为每个选项保留一个计数器,这样,您的文件,或者任何用于存储数据的后端都不会随着响应的到来而线性增长。
这样做会更容易,因为您无论如何都要创建计数器,这里唯一的区别是每次加载响应页面时都必须对所有项进行计数。
#initializing a variable with some mock poll data
option1 = "general store"
option2 = "supermarket"
option3 = "mall"
option4 = "small store"
sample_data = [option1,option2,option1,option1,option3,option3,option4,option4,option4,option2]
#a dict that will store the poll results
results = {}
for response in sample_data:
results[response] = results.setdefault(response, 0) + 1
现在,结果将把列表中发生的每一个字符串作为键,以及它作为值出现的次数。
发布于 2012-08-02 15:07:34
这样做是可行的:
>>> from collections import Counter
>>> data = ['Store', 'Office', 'Store', 'Office', 'Home', 'Nowhere']
>>> Counter(data)
Counter({'Office': 2, 'Store': 2, 'Home': 1, 'Nowhere': 1})
发布于 2012-08-02 14:57:42
您会想要使用collections.Counter
以及.most_common
方法。
https://stackoverflow.com/questions/11786997
复制相似问题