給出下面的例子,哪個更pythonic?使用函數組合,lambdas或(現在用於)完全不同的東西?我不得不說的是,Lambda表達式似乎更具可讀性,但圭多自己似乎要完全刪除lambda表達式 - http://www.artima.com/weblogs/viewpost.jsp?thread=98196什麼是pythonic - 功能組成,lambda或其他?
from functools import partial
from operator import not_, ge
def get_sql_data_type_from_string(s):
s = str(s)
# compose(*fs) -> returns composition of functions fs
# iserror(f, x) -> returns True if Exception thrown from f(x), False otherwise
# Using function composition
predicates = (
('int', compose(not_, partial(iserror, int))),
('float', compose(not_, partial(iserror, float))),
('char', compose(partial(ge, 1), len)))
# Using lambdas
predicates = (
('int', lambda x: not iserror(int, x)),
('float', lambda x: not iserror(float, x)),
('char', lambda x: len(x) <= 1))
# Test each predicate
for i, (t, p) in enumerate(predicates):
if p(s):
return i, t
# If all predicates fail
return (i + 1), 'varchar'
我認爲拉姆達的版本是最直接和明確的,這也是我想使它成爲最「Python的」。 –
nitpick - 根據你對iserror的定義,你應該像'iserror(int,x)'這樣的東西,而不是'iserror(int(x))'。 –
lambda的不錯 – pyCthon