Efficiently check if an element occurs at least n times in a list

后端 未结 7 2178
南旧
南旧 2020-12-07 00:23

How to best write a Python function (check_list) to efficiently test if an element (x) occurs at least n times in a list (l

7条回答
  •  遥遥无期
    2020-12-07 01:05

    Instead of incurring extra overhead with the setup of a range object and using all which has to test the truthiness of each item, you could use itertools.islice to advance the generator n steps ahead, and then return the next item in the slice if the slice exists or a default False if not:

    from itertools import islice
    
    def check_list(lst, x, n):
        gen = (True for i in lst if i==x)
        return next(islice(gen, n-1, None), False)
    

    Note that like list.count, itertools.islice also runs at C speed. And this has the extra advantage of handling iterables that are not lists.


    Some timing:

    In [1]: from itertools import islice
    
    In [2]: from random import randrange
    
    In [3]: lst = [randrange(1,10) for i in range(100000)]
    
    In [5]: %%timeit # using list.index
       ....: check_list(lst, 5, 1000)
       ....:
    1000 loops, best of 3: 736 µs per loop
    
    In [7]: %%timeit # islice
       ....: check_list(lst, 5, 1000)
       ....:
    1000 loops, best of 3: 662 µs per loop
    
    In [9]: %%timeit # using list.index
       ....: check_list(lst, 5, 10000)
       ....:
    100 loops, best of 3: 7.6 ms per loop
    
    In [11]: %%timeit # islice
       ....: check_list(lst, 5, 10000)
       ....:
    100 loops, best of 3: 6.7 ms per loop
    

提交回复
热议问题