在Python中使用Lambda [英] Using lambda in Python

查看:99
本文介绍了在Python中使用Lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用lambda对列表进行某种排序.我想做的是根据距起始位置的曼哈顿距离对坐标进行排序.我知道我的语法大部分都用完了,但是好像我缺少一些小东西,谢谢!

I am trying to use lambda do to some sorting on a list. What I wanted to do is sort the coordinates based on their manhattan distance from an inital poisition. I know I have most of the syntax down but it seems like I am missing something small, Thanks!

while (len(queue) > 0):  
    queue.sort(queue, lambda x: util.manhattanDistance(curr,x))  

推荐答案

您似乎正在尝试告诉sort()方法将lambda函数用作进行排序.这是通过关键字参数 key:

It appears that you're trying to tell the sort() method to use your lambda function as the key for sorting. This is done with the keyword argument key:

queue.sort(queue, key = [your lambda function])

重写的行是:

queue.sort(queue, key = lambda x: util.manhattanDistance(curr,x))

误解了原始lambda函数的用途;认为它是作为比较函数使用的,因为距离函数不能为负,所以没有意义

misunderstood the purpose of the original lambda function; thought it was intended as a comparison function, which doesn't make sense since distance functions can't be negative

这篇关于在Python中使用Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆