Python Lists - Finding Number of Times a String Occurs

后端 未结 8 411
独厮守ぢ
独厮守ぢ 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
    
    0 讨论(0)
  • 2020-12-10 17:31

    Use the count method. For example:

    (x, mylist.count(x)) for x in set(mylist)
    
    0 讨论(0)
  • 2020-12-10 17:33
    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
    
    0 讨论(0)
  • 2020-12-10 17:35

    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))
    
    0 讨论(0)
  • 2020-12-10 17:43

    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
    
    0 讨论(0)
  • 2020-12-10 17:47

    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)
    
    0 讨论(0)
提交回复
热议问题