简体   繁体   中英

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

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?

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]

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM