简体   繁体   English

Python lambda用作参数,从父函数调用其他参数

[英]Python lambda used as an argument, calling other arguments from parent function

I'm new to programming and am having a little trouble understanding the lambda function in Python. 我是编程新手,在理解Python中的lambda函数时遇到了一些麻烦。 I understand why it's used and its effectiveness. 我了解为什么使用它及其有效性。 Just having trouble learning to apply it. 只是在学习应用方面遇到困难。 I've read a guide and watched a lecture on using lambda as an argument. 我已阅读指南,并观看了有关使用lambda作为参数的演讲。 I've tried using the map function. 我试过使用地图功能。 Not sure if that's the correct approach, but this is my broken code in its most basic form: 不知道这是否是正确的方法,但这是我最基本形式的代码损坏:

def Coord(x, y, z=lambda: z*2 if z < x or z < y else z)):
    print(z)
Coord(10,20,30) 
Coord(10,20,12) 
Coord(10,20,8) 

Needs to return 30, 24, and 32, respectively. 需要分别返回30、24和32。 Working code without using lambda: 不使用lambda的工作代码:

def Coord(x, y, z):
    while z < x or z < y:
        z*=2
print(z)

You cannot use other parameters from the Coord function in your default parameter definition for z (which is a lambda function in your case). 您不能在z的默认参数定义中使用Coord函数中的其他参数(在您的情况下为lambda函数)。

You may want to do something like this: 您可能需要执行以下操作:

def Coord(x, y, w, z=lambda a,b,c: c*2 if c < a or c < b else c):
    print(z(x,y,w))

or 要么

def Coord(x, y, w):
    z=lambda: w*2 if w < x or w < y else w
    print(z())

Both definitions are equivalent when evaluating them with 3 arguments, and they result in: 当使用3个参数求值时,这两个定义是等效的,它们的结果是:

>>> Coord(10,20,30)
30
>>> Coord(10,20,12)
24
>>> Coord(10,20,8)
16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM