6

How would I find how many times each string appears in my list?

Say I have the word:

"General Store"

that is in my list like 20 times. How would I find out that it appears 20 times in my list? I need to know this so I can display that number as a type of "poll vote" answer.

E.g:

General Store - voted 20 times
Mall - voted 50 times
Ice Cream Van - voted 2 times

How would I display it in a fashion similar to this?:

General Store
20
Mall
50
Ice Cream Van
2
César
  • 9,939
  • 6
  • 53
  • 74
Aj Entity
  • 4,741
  • 4
  • 17
  • 13
  • 1
    Do you want it to be case-sensitive? – mgilson Aug 03 '12 at 17:54
  • I doubt that matters, as I can just print the letters first, and then use a for loop, count the number of occurrences, and put those in there. But yes, I want them to be case sensitive. :) – Aj Entity Aug 03 '12 at 18:30

8 Answers8

17

Use the count method. For example:

(x, mylist.count(x)) for x in set(mylist)
7

While the other answers (using list.count) do work, they can be prohibitively slow on large lists.

Consider using collections.Counter, as describe in http://docs.python.org/library/collections.html

Example:

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
dkamins
  • 21,450
  • 7
  • 55
  • 59
  • 3
    Why not just `cnt = Counter(['red','blue','red','green','blue','blue'])` ? As it is, you might as well be using `cnt = defaultdict(int)` -- which I suppose provides an O(N) way to do this in python 2.5 ... (as opposed to 2.7+ when Counter was introduced.) – mgilson Aug 03 '12 at 18:03
  • I only copied this example from the collections doc page linked, but yes the `Counter([iterable])` constructor is definitely cleaner and simpler! – dkamins Aug 04 '12 at 00:15
2

just a simple example:

   >>> lis=["General Store","General Store","General Store","Mall","Mall","Mall","Mall","Mall","Mall","Ice Cream Van","Ice Cream Van"]
   >>> for x in set(lis):
        print "{0}\n{1}".format(x,lis.count(x))


    Mall
    6
    Ice Cream Van
    2
    General Store
    3
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

First use set() to get all unique elements of the list. Then loop over the set to count elements from the list

unique = set(votes)
for item in unique:
    print item
    print votes.count(item)
Rajesh J Advani
  • 5,585
  • 2
  • 23
  • 35
  • This seems to be what I am looking for, and I understand looping, but I do not know about the set function. I tried looking on http://docs.python.org/library/functions.html#func-set but I still do not understand what I am setting. Maybe if you could explain what the votes is supposed to represent? Like I mean, do I put "General Store" in votes? But obviously that is supposed to go in "item" and you probably differentiated it for a reason. – Aj Entity Aug 03 '12 at 18:00
  • 1
    'votes' is your "list" containing duplicate strings that you want to count. And set() doesn't SET anything, it converts the list to a set by removing duplicates. – Rajesh J Advani Aug 03 '12 at 18:04
  • Ohh okay. I have got it to work now, but when I tried testing it, something like this occurs when I use the code: Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Grain Products 0 Fruits and Vegetables 0 Fruits and Vegetables 0 Fruits and Vegetables 0 Fruits and Vegetables 0 Fruits and Vegetables 0 Fruits and Vegetables 0 How would I make it just a single Category, getting all of the counts totalled in one place, and also, the – Aj Entity Aug 03 '12 at 18:11
  • count goes to 0 if the user hits a different radio button at that moment. The .data file contains all of the choices, but it does not keep their count from before. – Aj Entity Aug 03 '12 at 18:15
  • 1
    It looks like there is a lot more going on in your code that is not described here. Do you have a list/array object with all the strings for each vote? – Rajesh J Advani Aug 03 '12 at 18:21
  • I managed a small fix with this code: pollList = set(poll) grain = "Grain Products" fruit = "Fruits and Vegetables" meat = "Meats and Alternatives" dairy = "Dairy Products" print "

    Grain Products

    " for grain in pollList: print int(poll.count("Grain Products")) print "

    Fruits and Vegetables

    " for fruit in pollList: print poll.count("Fruits and Vegetables") print "

    Meats and Alternatives

    " for meat in pollList: print poll.count("Meats and Alternatives") print "

    Dairy Products" for dairy in pollList: print poll.count("Dairy Products") Now, just trying to

    – Aj Entity Aug 03 '12 at 18:22
  • get all of the counts into an added number. If the 0 did not appear there... maybe I could have collected and added all the 1's but with the others being 0, I do not know what to do. Here is a portion of my output now: – Aj Entity Aug 03 '12 at 18:24
  • Grain Products 1 1 1 1 1 1 1 1 1 1 1 1 1 Fruits and Vegetables 0 0 0 0 0 0 0 0 0 0 0 0 0 Meats and Alternatives 0 0 0 0 0 0 0 0 0 0 0 0 0 Dairy Products 0 0 0 0 0 0 0 0 0 0 0 0 0 – Aj Entity Aug 03 '12 at 18:25
  • These are my scripts in case you need to know more info as to what I am messing up and my explanations come short: http://pastebin.com/mDxEWnCX http://pastebin.com/tbgXtpZz – Aj Entity Aug 03 '12 at 18:32
1

I like one-line solutions to problems like this:

def tally_votes(l):
  return map(lambda x: (x, len(filter(lambda y: y==x, l))), set(l))
jimaltieri
  • 61
  • 4
  • 1
    I would imagine `list.count(x)` is more efficient than `len(filter(...))`. –  Aug 03 '12 at 18:19
1

You can use a dictionary, you might want to consider just using a dictionary from the beginning instead of a list but here is a simple setup.

#list
mylist = ['General Store','Mall','Ice Cream Van','General Store']

#takes values from list and create a dictionary with the list value as a key and
#the number of times it is repeated as their values
def votes(mylist):
d = dict()
for value in mylist:
    if value not in d:
        d[value] = 1
    else:
        d[value] +=1

return d

#prints the keys and their vaules
def print_votes(dic):
    for c in dic:
        print c +' - voted', dic[c], 'times'

#function call
print_votes(votes(mylist))

It outputs:

Mall - voted 1 times
Ice Cream Van - voted 1 times
General Store - voted 2 times
jkdba
  • 2,378
  • 3
  • 23
  • 33
0

If you're willing to use the pandas library, this one is really quick:

import pandas as pd 

my_list = lis=["General Store","General Store","General Store","Mall","Mall","Mall","Mall","Mall","Mall","Ice Cream Van"]
pd.Series(my_list).value_counts()
Michael Discenza
  • 3,240
  • 7
  • 30
  • 41
-1
votes=["General Store", "Mall", "General Store","Ice Cream Van","General Store","Ice Cream Van","Ice Cream Van","General Store","Ice Cream Van"]

for vote in set(votes):
    print(vote+" - voted "+str(votes.count(vote))+" times")

Try this. It will output

General Store - voted 4 times
Ice Cream Van - voted 4 times
Mall - voted 1 times
Amit Ghosh
  • 1,500
  • 13
  • 18