Check if all elements in a list are identical

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

    Or use diff method of numpy:

    import numpy as np
    def allthesame(l):
        return np.unique(l).shape[0]<=1
    

    And to call:

    print(allthesame([1,1,1]))
    

    Output:

    True

    0 讨论(0)
  • 2020-11-22 08:04
    lambda lst: reduce(lambda a,b:(b,b==a[0] and a[1]), lst, (lst[0], True))[1]
    

    The next one will short short circuit:

    all(itertools.imap(lambda i:yourlist[i]==yourlist[i+1], xrange(len(yourlist)-1)))
    
    0 讨论(0)
  • 2020-11-22 08:05
    >>> a = [1, 2, 3, 4, 5, 6]
    >>> z = [(a[x], a[x+1]) for x in range(0, len(a)-1)]
    >>> z
    [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
    # Replacing it with the test
    >>> z = [(a[x] == a[x+1]) for x in range(0, len(a)-1)]
    >>> z
    [False, False, False, False, False]
    >>> if False in z : Print "All elements are not equal"
    
    0 讨论(0)
  • 2020-11-22 08:06

    Use itertools.groupby (see the itertools recipes):

    from itertools import groupby
    def all_equal(iterable):
        g = groupby(iterable)
        return next(g, True) and not next(g, False)
    

    or without groupby:

    def all_equal(iterator):
        iterator = iter(iterator)
        try:
            first = next(iterator)
        except StopIteration:
            return True
        return all(first == rest for rest in iterator)
    

    There are a number of alternative one-liners you might consider:

    1. Converting the input to a set and checking that it only has one or zero (in case the input is empty) items

      def all_equal2(iterator):
          return len(set(iterator)) <= 1
      
    2. Comparing against the input list without the first item

      def all_equal3(lst):
          return lst[:-1] == lst[1:]
      
    3. Counting how many times the first item appears in the list

      def all_equal_ivo(lst):
          return not lst or lst.count(lst[0]) == len(lst)
      
    4. Comparing against a list of the first element repeated

      def all_equal_6502(lst):
          return not lst or [lst[0]]*len(lst) == lst
      

    But they have some downsides, namely:

    1. all_equal and all_equal2 can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.
    2. all_equal and all_equal3 stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer is False just by looking at the first two elements.
    3. In all_equal2 the content must be hashable. A list of lists will raise a TypeError for example.
    4. all_equal2 (in the worst case) and all_equal_6502 create a copy of the list, meaning you need to use double the memory.

    On Python 3.9, using perfplot, we get these timings (lower Runtime [s] is better):

    0 讨论(0)
  • 2020-11-22 08:06

    I'd do:

    not any((x[i] != x[i+1] for i in range(0, len(x)-1)))
    

    as any stops searching the iterable as soon as it finds a True condition.

    0 讨论(0)
  • 2020-11-22 08:09

    Regarding using reduce() with lambda. Here is a working code that I personally think is way nicer than some of the other answers.

    reduce(lambda x, y: (x[1]==y, y), [2, 2, 2], (True, 2))
    

    Returns a tuple where the first value is the boolean if all items are same or not.

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