Check if all elements in a list are identical

前端 未结 22 1922
死守一世寂寞
死守一世寂寞 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 08:10
    def allTheSame(i):
        j = itertools.groupby(i)
        for k in j: break
        for k in j: return False
        return True
    

    Works in Python 2.4, which doesn't have "all".

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

    For what it's worth, this came up on the python-ideas mailing list recently. It turns out that there is an itertools recipe for doing this already:1

    def all_equal(iterable):
        "Returns True if all the elements are equal to each other"
        g = groupby(iterable)
        return next(g, True) and not next(g, False)
    

    Supposedly it performs very nicely and has a few nice properties.

    1. Short-circuits: It will stop consuming items from the iterable as soon as it finds the first non-equal item.
    2. Doesn't require items to be hashable.
    3. It is lazy and only requires O(1) additional memory to do the check.

    1In other words, I can't take the credit for coming up with the solution -- nor can I take credit for even finding it.

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

    Doubt this is the "most Pythonic", but something like:

    >>> falseList = [1,2,3,4]
    >>> trueList = [1, 1, 1]
    >>> 
    >>> def testList(list):
    ...   for item in list[1:]:
    ...     if item != list[0]:
    ...       return False
    ...   return True
    ... 
    >>> testList(falseList)
    False
    >>> testList(trueList)
    True
    

    would do the trick.

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

    You can do:

    reduce(and_, (x==yourList[0] for x in yourList), True)
    

    It is fairly annoying that python makes you import the operators like operator.and_. As of python3, you will need to also import functools.reduce.

    (You should not use this method because it will not break if it finds non-equal values, but will continue examining the entire list. It is just included here as an answer for completeness.)

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