Check if all elements in a list are identical

前端 未结 22 1918
死守一世寂寞
死守一世寂寞 2020-11-22 07:45

I need a function which takes in a list and outputs True if all elements in the input list evaluate as equal to each other using the standard equal

22条回答
  •  隐瞒了意图╮
    2020-11-22 07:59

    A solution faster than using set() that works on sequences (not iterables) is to simply count the first element. This assumes the list is non-empty (but that's trivial to check, and decide yourself what the outcome should be on an empty list)

    x.count(x[0]) == len(x)
    

    some simple benchmarks:

    >>> timeit.timeit('len(set(s1))<=1', 's1=[1]*5000', number=10000)
    1.4383411407470703
    >>> timeit.timeit('len(set(s1))<=1', 's1=[1]*4999+[2]', number=10000)
    1.4765670299530029
    >>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*5000', number=10000)
    0.26274609565734863
    >>> timeit.timeit('s1.count(s1[0])==len(s1)', 's1=[1]*4999+[2]', number=10000)
    0.25654196739196777
    

提交回复
热议问题