Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True
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 other case -> False
This is my try at it:
>>> def consistent(x):
... x_filtered = filter(None, x)
... return len(x_filtered) in (0, len(x))
...
>>> consistent((0,1))
Fals开发者_Go百科e
>>> consistent((1,1))
True
>>> consistent((0,0))
True
[Bonus]
What should this function be named?
def unanimous(it):
it1, it2 = itertools.tee(it)
return all(it1) or not any(it2)
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
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.
def all_equals(xs):
x0 = next(iter(xs), False)
return all(bool(x) == bool(x0) for x in xs)
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)
Just yet another way of doing it, given list l:
sum([int(bool(x)) for x in l]) in (0, len(l))
>>> a=['',None,0,False]
>>> b=[1,True,'ddd']
>>> c=[0,1,False,True,None]
>>> for l in (a,b,c):
... print sum([int(bool(x)) for x in l]) in (0, len(l))
...
True
True
False
def AllTheSame(iterable):
return any(iterable) is all(iterable)
精彩评论