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

前端 未结 7 722
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题