2010-11-30 86 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) 
相關問題