[英]How to apply lambda function in for loop
I am learning how to use lambda functions in for loop and faced with this我正在学习如何在 for 循环中使用 lambda 函数并面临这个问题
l3=['one','two','three']
for i in l3:
lambda i: i.upper()
print(i)
I expect that each member of my list will be in uppercase but output is the same in lower case.我希望我的列表中的每个成员都是大写的,但输出是小写的。 What i am doing wrong ?我做错了什么?
as others comment, you are printing the variable i and not calling at all the lambda正如其他人评论的那样,您正在打印变量 i 而根本没有调用 lambda
try instead:改为尝试:
x = lambda i: i.upper()
print(x(i))
You're defining a lambda but you're never calling it.您正在定义一个 lambda,但您从未调用过它。 What you probably meant is你可能的意思是
l3 = ['one','two','three']
for i in l3:
i = (lambda x: x.upper())(i)
print(i)
or或者
l3 = ['one','two','three']
for i in l3:
f = lambda x: x.upper()
print(f(i))
Which are not good examples on how to use a lambda anyway.无论如何,这都不是关于如何使用 lambda 的好例子。
Also, notice that I'm calling the parameter x
instead of i
, since that i
inside the lambda wouldn't be the same i
you're using to iterate the list.另外注意,我调用参数x
,而不是i
,自认为i
的拉姆达内会不一样i
你使用迭代列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.