Python Lists - Find the Number of Times a String Occurs

How can I find out how many times each line appears in my list?

Say I have a word:

"General Store"

what's on my list like 20 times. How do I know that he appears 20 times on my list? I need to know this, so I can display this number as a response type "poll vote".

eg:

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

How can I display it just like that ?:

General Store
20
Mall
50
Ice Cream Van
2
+5
source share
6 answers

Use the method count. For instance:

(x, mylist.count(x)) for x in set(mylist)
+14
source

While other answers (using list.count) work, they can be excessively slow in large lists.

Consider use collections.Counteras described at http://docs.python.org/library/collections.html

:

>>> # 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})
+4

:

   >>> 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
+2

First use set () to get all the unique elements of the list. Then move on to the set to count the items from the list.

unique = set(votes)
for item in unique:
    print item
    print votes.count(item)
+1
source

I like single-line solutions to such problems:

def tally_votes(l):
  return map(lambda x: (x, len(filter(lambda y: y==x, l))), set(l))
+1
source

You can use a dictionary, you may just need to use a dictionary from the very beginning, not 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
+1
source

All Articles