python counting elements in iterable with filter

后端 未结 1 1447
北海茫月
北海茫月 2021-01-28 16:01

To count the elements in a list, you can use collections.Counter, but what if only some of the elements have to be counted?

I\'ve set up this example (please note: numpy

相关标签:
1条回答
  • 2021-01-28 16:41

    If this is about large numpy arrays you'd better take advantage of vectorized numpy operations.

    %%time
    np.unique(numbers[numbers <= 10], return_counts=True)
    

    Output:

    Wall time: 31.2 ms
    
    (array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10]),
     array([10055, 10090,  9941, 10002,  9994,  9989, 10070,  9859, 10038,
            10028,  9965], dtype=int64))
    

    ​For comparison, my own timing of your code gave slighly higher times than yours.

    0 讨论(0)
提交回复
热议问题