Python Lists - Finding Number Of Times A String Occurs
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 time
Solution 1:
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})
Solution 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 inset(lis):
print"{0}\n{1}".format(x,lis.count(x))
Mall
6
Ice Cream Van
2
General Store
3
Solution 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 inunique:
print item
print votes.count(item)
Solution 4:
I like one-line solutions to problems like this:
deftally_votes(l):
returnmap(lambda x: (x, len(filter(lambda y: y==x, l))), set(l))
Solution 5:
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 valuesdefvotes(mylist):
d = dict()
for value in mylist:
if value notin d:
d[value] = 1else:
d[value] +=1return d
#prints the keys and their vaulesdefprint_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
Post a Comment for "Python Lists - Finding Number Of Times A String Occurs"