Python Lists - Finding Number of Times a String Occurs

后端 未结 8 436
独厮守ぢ
独厮守ぢ 2020-12-10 17:21

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

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 17:27

    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
    

提交回复
热议问题