2010-11-30 89 views
11

我想要的功能的结果是:Python的方式来检查:所有元素评估为False - 或 - 所有元素评估为True

  • 所有值评估为假(无,0,空字符串) - >真
  • 所有值评估为True - >真
  • 任何其他情况下 - >假

这是我尝试它:

>>> def consistent(x): 
... x_filtered = filter(None, x) 
... return len(x_filtered) in (0, len(x)) 
... 
>>> consistent((0,1)) 
False 
>>> consistent((1,1)) 
True 
>>> consistent((0,0)) 
True 

[奖金]

该函数应该命名为什么?

回答

23
def unanimous(it): 
    it1, it2 = itertools.tee(it) 
    return all(it1) or not any(it2) 
-1
def AllTheSame(iterable): 
    return any(iterable) is all(iterable) 
2

捎带上伊格纳西奥巴斯克斯 - 亚伯兰的方法,但是第一个不匹配后,将停止:

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)) 

虽然使用not reduce(operators.xor, s)会更简单,它不会短路。

1
def all_equals(xs): 
    x0 = next(iter(xs), False) 
    return all(bool(x) == bool(x0) for x in xs) 
0

并非如此短暂,但没有捷径用“三通”之类的东西上浪费。

def unanimous(s): 
    s = iter(s) 
    if s.next(): 
     return all(s) 
    else: 
     return not any(s) 
相关问题