Python版的C++ all_of

nht*_*rnm 3 c++ python built-in

有没有更好的方法(使用内置函数)来重写下面的代码:

def all_of(iterable, predicate):
    for elem in iterable:
        if not predicate(elem):
            return False
    return True
Run Code Online (Sandbox Code Playgroud)

Pav*_*sov 7

all 是内置的:

all(predicate(e) for e in iterable)
Run Code Online (Sandbox Code Playgroud)

 

我不认为定义这样的东西是值得的:

def all_of(iterable, predicate):
    return all(predicate(e) for e in iterable)
Run Code Online (Sandbox Code Playgroud)