【问题标题】:What is more pythonic - function composition, lambdas, or something else? [closed]什么是更 Pythonic - 函数组合、lambdas 或其他东西? [关闭]
【发布时间】:2012-08-27 08:31:59
【问题描述】:

给定下面的例子,哪个更pythonic?使用函数组合、lambdas 或 (现在是)完全不同的东西?我不得不说 lambdas 似乎更具可读性,但 Guido 本人似乎想完全删除 lambdas - http://www.artima.com/weblogs/viewpost.jsp?thread=98196

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'

【问题讨论】:

  • 我认为 lambda 版本是最直接和清晰的,我也认为它是最“pythonic”的。
  • nitpick -- 根据你对 iserror 的定义,你应该有类似 iserror(int,x) 的东西,而不是 iserror(int(x))
  • @Vaugn Cato 谢谢!相应地更新了问题

标签: python function lambda functional-programming composition


【解决方案1】:

从未见过 Python 的程序员一眼就能认出 lambda。我已经使用 Python 十多年了,我一直在摸索组合形式,即使与 lambda 版本进行比较也是如此。

选择不烂的。此外,鉴于 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多