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 t
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
Use the count
method. For example:
(x, mylist.count(x)) for x in set(mylist)
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
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))
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
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)