Home > OS >  Is there a faster way I can count the number of occurrences of a number in a list?
Is there a faster way I can count the number of occurrences of a number in a list?

Time:06-01

I am trying to write a function to count the occurrences of a number in a list, and the order is ascending according to the number (from 0 to the maximum value in the list), not the occurrences. Here's the function I wrote:

def sort_counts(sample):
    result = []
    for i in range(max(sample) 1):
        result.append(sample.count(i))
    return result

For example:

>>> sort_counts([1,2,2,3,3,4,1,1,1,1,2,5])
>>> [0, 5, 3, 2, 1, 1]

I learned that sample.count would work slowly if there are more numbers in the list. Is there a faster/simpler way I can write this function?

CodePudding user response:

Counter from collections module is a nice way to count the number of occurrences of items in a list

from collections import Counter
lst = [1,2,2,3,3,4,1,1,1,1,2,5]
# create a counter object
c = Counter(lst)
# get the counts
[c[i] for i in range(max(c) 1)]
# [0, 5, 3, 2, 1, 1]

CodePudding user response:

If you don't want to use a counter, then you can simply iterate over the values in the list after creating a result array of the appropriate size beforehand:

sample = [1,2,2,3,3,4,1,1,1,1,2,5]
result = [0] * (max(sample) 1)
for v in sample:
    result[v]  = 1

Output:

[0, 5, 3, 2, 1, 1]

Speed wise for your sample data, if the Counter solution is 1x time, this is about 4x and your existing solution about 8x. As the lists get longer, the speed advantage of Counter decreases and the relative performance is more like 1x, 2x and 4x.

CodePudding user response:

If you don't want to use count iterate through the elements of the samples and update the result. It can reduce the time required for multiple traversal required to find the count of the element.

def sort_counts(sample):
    result = [0]*(max(sample) 1)
    for s in samples:
        result[s] =1
    return result
  • Related