7

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
2
  • 1
    Do you want it to be case-sensitive? Commented Aug 3, 2012 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. :) Commented Aug 3, 2012 at 18:30

8 Answers 8

17

Use the count method. For example:

(x, mylist.count(x)) for x in set(mylist)
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.)
I only copied this example from the collections doc page linked, but yes the Counter([iterable]) constructor is definitely cleaner and simpler!
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

Comments

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)

9 Comments

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 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.
'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.
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
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.
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?
|
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))

1 Comment

I would imagine list.count(x) is more efficient than len(filter(...)).
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

Comments

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

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.