2012-09-02 28 views
8

給出下面的例子,哪個更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' 
+1

我認爲拉姆達的版本是最直接和明確的,這也是我想使它成爲最「Python的」。 –

+2

nitpick - 根據你對iserror的定義,你應該像'iserror(int,x)'這樣的東西,而不是'iserror(int(x))'。 –

+0

lambda的不錯 – pyCthon

回答

8

誰從未見過的Python就能一眼找出拉姆達程序員。我已經使用了Python十多年了,我正在摸索着解決組合表單的問題,即使使用lambda版本進行比較。

去找一個不吸吮的人。另外,鑑於拉姆達做出了3.0的裁減,我懷疑它是否會被刪除。

2

這裏是會落入「不同」類別的方法:

def get_sql_data_type_from_string(s): 
    s = str(s) 

    def char(x): 
     if len(x)<=1: 
      return x 
     raise RuntimeError('Not a char') 

    predicates = (
     ('int',  int), 
     ('float', float), 
     ('char', char) 
    ) 

    # Test each predicate 
    for i, (t, p) in enumerate(predicates): 
     try: 
      p(s) 
      return i,t 
     except: 
      pass 

    # If all predicates fail 
    return (i + 1), 'varchar' 
相關問題