简体   繁体   English

在zip()的for循环中使用lambda

[英]using lambda in a for loop with zip()

Hello guys I've been playing today a bit with python and got a bit confused while using the lambda fucntion. 大家好,我今天一直在用python玩游戏,使用lambda功能时有些困惑。 My original intention was to subtract the value of each element in a vector with the values form a second vector and introduce all the results in a 3rd vector. 我的初衷是减去向量中每个元素的值,然后将值形成第二个向量,并将所有结果引入第三个向量中。 Went like this: 像这样去了:

v1=[1, 2, 3, 4]
v2 =[7,2 ,7 ,6]
v3=[x-y for x,y in zip(v1,v2)]

then I though to calculate using the same structure the absolute value using a lambda function and I tried this: 然后我虽然使用lambda函数使用相同的结构来计算绝对值,但我尝试这样做:

v1=[1, 2, 3, 4]
v2 =[7,2 ,7 ,6]
[lambda x,y: x-y if x>y else y-x for x,y in zip(v1,v2)]

this only gives memory locations I think. 我只给出了内存位置。 and I don't know why , wehre I did wrong? 而且我不知道为什么,我做错了吗?

It gives you a bunch of lambda functions. 它为您提供了一堆lambda函数。 All you did there is define the function, but you never call it. 您在其中所做的只是定义函数,但从未调用它。 Do this instead: 改为这样做:

[(lambda x,y: x-y if x>y else y-x)(x,y) for x,y in zip(v1,v2)]

You really don't need a function, though. 不过,您实际上不需要功能。 Just do it like this: 像这样做:

[(x-y if x>y else y-x) for x,y in zip(v1,v2)]

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

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