相关疑难解决方法(0)

它是pythonic:命名lambdas

我开始意识到python中lambda表达式的价值,特别是涉及函数式编程map,函数返回函数等等.但是,我也一直在函数中命名lambdas,因为:

  • 我需要多次使用相同的功能,不想重复代码.
  • 该功能特定于其出现的功能; 其他地方不需要它.

当我遇到满足上述标准的情况时,我一直在编写一个名为lambda的表达式,以便干燥并缩小范围功能.例如,我正在编写一个在某些numpy数组上运行的函数,我需要对传递给函数的所有数组进行适度的繁琐索引(可以很容易地放在一行上).我编写了一个名为lambda的表达式来进行索引,而不是编写整个其他函数,或者在整个函数定义中多次复制/粘贴索引.

def fcn_operating_on_arrays(array0, array1):
    indexer = lambda a0, a1, idx: a0[idx] + a1[idx]

    # codecodecode

    indexed = indexer(array0, array1, indices)

    # codecodecode in which other arrays are created and require `indexer`

    return the_answer
Run Code Online (Sandbox Code Playgroud)

这是滥用python的lambdas吗?我应该吮吸它并定义一个单独的功能吗?

编辑

可能值得链接功能内部功能.

python lambda

9
推荐指数
2
解决办法
3914
查看次数

如何在lambda中指定参数类型?

对于常用功能,您可以按如下方式注释类型

def my_function(arg1: int)
Run Code Online (Sandbox Code Playgroud)

我怎么在lambda中这样做?

lambda a: int, b: int : a+b
Run Code Online (Sandbox Code Playgroud)

给出语法错误.

python lambda

6
推荐指数
1
解决办法
2445
查看次数

将lambda函数类型化为函数参数

我有一个接受lambda的函数:

def my_function(some_lambda):
  # do stuff
  some_other_variable = some_lambda(some_variable)

my_function(lambda x: x + 2)
Run Code Online (Sandbox Code Playgroud)

我想输入传递的lambda函数.

我试过了

def my_function(some_lambda: lambda) -> None:
# SyntaxError: invalid syntax
from typing import Lambda
# ImportError: cannot import name 'Lambda'
Run Code Online (Sandbox Code Playgroud)

我的IDE在2.7跨式类型提示上抱怨类似的东西,例如

def my_function(some_lambda: lambda) -> None:
  # type: (lambda) -> None
# formal parameter name expected
Run Code Online (Sandbox Code Playgroud)

python type-hinting python-2.7 python-3.x

4
推荐指数
1
解决办法
380
查看次数

标签 统计

python ×3

lambda ×2

python-2.7 ×1

python-3.x ×1

type-hinting ×1