1

Possible Duplicate:
How to calculate the occurrences of a list item in Python?

I am making a sort of poll. For that, I am using Python, and the part I am stuck at is trying to figure out how to count the number of times a certain thing, say, "General Store" shows up.

E.g. of Poll:

Where do you see advertisements the most?

  1. General Store

  2. Supermarket

  3. Mall

  4. Small Stores

The poll data is submitted via radio buttons if that information is needed. All of these answers would be appended to a list, and then I want to create a results page that shows how many times each thing was voted on.

Community
  • 1
  • 1
Aj Entity
  • 4,741
  • 4
  • 17
  • 13

5 Answers5

7

This works:

>>> from collections import Counter
>>> data = ['Store', 'Office', 'Store', 'Office', 'Home', 'Nowhere']
>>> Counter(data)
Counter({'Office': 2, 'Store': 2, 'Home': 1, 'Nowhere': 1})
dawg
  • 98,345
  • 23
  • 131
  • 206
3

first of all, I'm going to say you're probably using the wrong sollution for your poll results problem. Why not keep a counter for each option, this way, your file, or whatever backend you're using to store this data won't grow linearly as responses come in.

The reason that would be easier, is because you'll be creating counters anyway, with the only difference here that you'll have to count all the items every time the responses page is loaded.

#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

now, results will have every string that occurred in the list as a key, and the number of times it occurred as it's value.

bigblind
  • 12,539
  • 14
  • 68
  • 123
2

You will want to use collections.Counter

and the .most_common method.

jamylak
  • 128,818
  • 30
  • 231
  • 230
2

For Python 2.7+, you can use 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)]

If you are not on 2.7, you can do this instead:

>>> s = set(l)
>>> d = {}
>>> for i in s:
...    d[i] = l.count(i)
... 
>>> d
{'there': 1, 'bar': 1, 'hello': 3, 'foo': 2}
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • `l` is a bad variable name since it can be confused with `1`. http://www.python.org/dev/peps/pep-0008/ – jamylak Aug 02 '12 at 23:18
1

If you have a list, you can do

ls = ["Mall", "Mall", "Supermarket"]
ls.count("Mall")
>>> 2
ls.count("General Store")
>>> 0
Calvin Jia
  • 856
  • 5
  • 5