Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True

前端 未结 7 736
無奈伤痛
無奈伤痛 2021-02-02 17:33

I want the results of the function to be:

  • All values evaluate to False (None, 0, empty string) -> True
  • All values evaluate to True -> True
  • Every
相关标签:
7条回答
  • 2021-02-02 18:00
    def AllTheSame(iterable):
        return any(iterable) is all(iterable)
    
    0 讨论(0)
  • 2021-02-02 18:06
    def unanimous(it):
      it1, it2 = itertools.tee(it)
      return all(it1) or not any(it2)
    
    0 讨论(0)
  • 2021-02-02 18:09

    Piggybacking on Ignacio Vasquez-Abram's method, but will stop after first mismatch:

    def unanimous(s):
      it1, it2 = itertools.tee(iter(s))
      it1.next()
      return not any(bool(a)^bool(b) for a,b in itertools.izip(it1,it2))
    

    While using not reduce(operators.xor, s) would be simpler, it does no short-circuiting.

    0 讨论(0)
  • 2021-02-02 18:10

    Not so brief, but shortcuts without messing around with 'tee' or anything like that.

    def unanimous(s):
       s = iter(s)
       if s.next():
           return all(s)
       else:
           return not any(s)
    
    0 讨论(0)
  • 2021-02-02 18:12
    def all_equals(xs):
        x0 = next(iter(xs), False)
        return all(bool(x) == bool(x0) for x in xs)
    
    0 讨论(0)
  • 2021-02-02 18:24
    def all_bools_equal(lst):
        return all(lst) or not any(lst)
    

    See: http://docs.python.org/library/functions.html#all

    See: http://docs.python.org/library/functions.html#any

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