Python Lists - Finding Number of Times a String Occurs

后端 未结 8 412
独厮守ぢ
独厮守ぢ 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:48

    If you're willing to use the pandas library, this one is really quick:

    import pandas as pd 
    
    my_list = lis=["General Store","General Store","General Store","Mall","Mall","Mall","Mall","Mall","Mall","Ice Cream Van"]
    pd.Series(my_list).value_counts()
    
    0 讨论(0)
  • 2020-12-10 17:53

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