Check if all elements in a list are identical

前端 未结 22 1920
死守一世寂寞
死守一世寂寞 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:53

    This is another option, faster than len(set(x))==1 for long lists (uses short circuit)

    def constantList(x):
        return x and [x[0]]*len(x) == x
    
    0 讨论(0)
  • 2020-11-22 07:54

    You can use .nunique() to find number of unique items in a list.

    def identical_elements(list):
        series = pd.Series(list)
        if series.nunique() == 1: identical = True
        else:  identical = False
        return identical
    
    
    
    identical_elements(['a', 'a'])
    Out[427]: True
    
    identical_elements(['a', 'b'])
    Out[428]: False
    
    0 讨论(0)
  • 2020-11-22 07:55

    Check if all elements equal to the first.

    np.allclose(array, array[0])

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 07:59

    If you're interested in something a little more readable (but of course not as efficient,) you could try:

    def compare_lists(list1, list2):
        if len(list1) != len(list2): # Weed out unequal length lists.
            return False
        for item in list1:
            if item not in list2:
                return False
        return True
    
    a_list_1 = ['apple', 'orange', 'grape', 'pear']
    a_list_2 = ['pear', 'orange', 'grape', 'apple']
    
    b_list_1 = ['apple', 'orange', 'grape', 'pear']
    b_list_2 = ['apple', 'orange', 'banana', 'pear']
    
    c_list_1 = ['apple', 'orange', 'grape']
    c_list_2 = ['grape', 'orange']
    
    print compare_lists(a_list_1, a_list_2) # Returns True
    print compare_lists(b_list_1, b_list_2) # Returns False
    print compare_lists(c_list_1, c_list_2) # Returns False
    
    0 讨论(0)
  • 2020-11-22 07:59

    Can use map and lambda

    lst = [1,1,1,1,1,1,1,1,1]
    
    print all(map(lambda x: x == lst[0], lst[1:]))
    
    0 讨论(0)
提交回复
热议问题