2012-08-02 47 views
0

可能重复:
How to calculate the occurrences of a list item in Python?列表 - 如何找到次数的项目出现

我想提出一个排序投票。为此,我使用的是Python,而我所坚持的部分是试图弄清楚如何计算某个特定事物(例如“General Store”)出现的次数。

E.g.投票:

你在哪看到广告最?

  1. 一般商店

  2. 超市

  3. 商城

  4. 小商店

是否需要该信息的调查数据是通过单选按钮提交。所有这些答案将被追加到一个列表中,然后我想创建一个结果页面,显示每个事物被投票的次数。

回答

3

首先,我要你可能使用了错误的sollution的说你投票结果问题。为什么不为每个选项保留一个计数器,这样,你的文件,或任何你用来存储这些数据的后端将不会随着响应的增加而线性增长。

之所以会更容易,是因为你无论如何,我会创建计数器,唯一不同的是,每次加载响应页时,您都必须对所有项目进行计数。

#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 

现在,结果将在每次发生在列表中的一个关键字符串,它的发生,因为它是值的次数。

2

你将要使用collections.Counter

.most_common方法。

+1

需要注意的是,如果你有Python的这只适用2.7+ – 2012-08-02 23:03:46

+0

@BurhanKhalid这个链接解释了这个问题,并且有Py 2.5的代码链接 – jamylak 2012-08-02 23:17:52

1

如果你有一个列表,你可以做

​​
6

这工作:

>>> from collections import Counter 
>>> data = ['Store', 'Office', 'Store', 'Office', 'Home', 'Nowhere'] 
>>> Counter(data) 
Counter({'Office': 2, 'Store': 2, 'Home': 1, 'Nowhere': 1}) 
1

对于Python 2.7+,您可以使用collections.Counter

>>> from collections import Counter 
>>> l = ['hello','hello','hello','there','foo','foo','bar'] 
>>> Counter(l).most_common() 
[('hello', 3), ('foo', 2), ('there', 1), ('bar', 1)] 

如果你不是在2.7,你可以这样做,而不是:

>>> s = set(l) 
>>> d = {} 
>>> for i in s: 
... d[i] = l.count(i) 
... 
>>> d 
{'there': 1, 'bar': 1, 'hello': 3, 'foo': 2} 
+0

'l'是一个不好的变量名,因为它可能与'1'混淆。 http://www.python.org/dev/peps/pep-0008/ – jamylak 2012-08-02 23:18:23

相关问题