[英]i want to return two values from one lambda and assign to the other one but i got error
I had tried to return values to a and b by using the below method我曾尝试使用以下方法将值返回给 a 和 b
(lambda a,b:print(a,b))((lambda x:(x,[int(i)**len(x) for i in x]))('153'))
but this shows error,i need some help to fix this.但这显示错误,我需要一些帮助来解决这个问题。
TypeError: <lambda>() missing 1 required positional argument: 'b'
The inner function returns a single tuple of two values, but the outer function expects two separate values.内部 function 返回两个值的单个元组,但外部 function 需要两个单独的值。 Use
*
-unpacking to have each value of the tuple passed as a separate parameter:使用
*
-unpacking将元组的每个值作为单独的参数传递:
# v takes two parameters v provides one tuple of two values
(lambda a,b:print(a,b))(*(lambda x:(x,[int(i)**len(x) for i in x]))('153'))
# ^ unpack operator
Note that print
already takes positional arguments – (lambda a,b:print(a,b))
can be replaced by just print
.请注意,
print
已经占据了位置 arguments - (lambda a,b:print(a,b))
可以仅替换为print
。 Also, Python3.8 introduces the :=
assignment operator, which can often be used instead of a lambda
to emulate let
expressions.此外,Python3.8 引入了
:=
赋值运算符,它通常可以用来代替lambda
来模拟let
表达式。 This shortens the expression significantly:这显着缩短了表达式:
# v print takes multiple arguments
print(*(x := '153', [int(i)**len(x) for i in x]))
# ^ assignment operator binds in current scope
@MisterMiyagi posted the correct answer using the given structure. @MisterMiyagi 使用给定的结构发布了正确答案。 However, I can't think of a case where using two lambdas in the way you did would be useful.
但是,我想不出以您的方式使用两个 lambda 表达式会有用的情况。 Defining a function would make the code much more readable:
定义 function 将使代码更具可读性:
def print_values(string):
values = [int(i)**len(string) for i in string]
print(string, values)
print_values("153")
Or if you want it shorter:或者,如果您希望它更短:
def print_values(string):
print(string, [int(i)**len(string) for i in string])
print_values("153")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.