简体   繁体   English

如何将此lambda命令转换为Python中的函数?

[英]How to convert this lambda command to a function in Python?

How could I convert the following line of code using a lambda command into a function by itself? 我如何使用lambda命令将以下代码行本身转换为函数?

I am struggling to get the hang of lambda, and wanted to apply it to an example I found. 我正在努力获取lambda的精髓,并想将其应用于我发现的示例。 I am confused about how to convert the x and y when I put it in it's own function, like def sortedList(myList) 我对如何将xy放入自己的函数中时感到困惑,例如def sortedList(myList)

The line with the lambda is as follows: 带有lambda的行如下:

myList = [[1,2],[19,20],[2,3]]    
listNums = sorted(myList, 
                      sortList = lambda x,y: x[0] + y[0] if x[0] == y[0] else y[1] - x[1])
listNums = sorted(myList, 
                  sortList = lambda x,y: x[0] + y[0] if x[0] == y[0] else y[1] - x[1])

is equivalent to 相当于

def funcname(x,y):
    return x[0] + y[0] if x[0] == y[0] else y[1] - x[1]

listNums = sorted(myList, sortList=funcname)

However, that is not the correct syntax for sorted - it should be 但是,这不是用于sorted的正确语法-应该是

listNums = sorted(mylist, cmp=funcname)

To address your comment, sorted uses the cmp function to sort the elements of your list. 为了解决您的评论,sorted使用cmp函数对列表中的元素进行排序。 In your question, your list is [[1,2],[19,20],[2,3]] . 在您的问题中,您的列表为[[1,2],[19,20],[2,3]] The basic question is, which comes first [1,2] or [19,20] ? 基本问题是,哪个先出现[1,2][19,20] Because that question could be answered nearly infinite different ways, it lets you provide the answer with a cmp function. 因为可以几乎无限不同的方式回答该问题,所以可以为您提供带有cmp函数的答案。 In that case, to decide which of those pairs comes first, sorted will run cmp(x=[1,2], y=[19,20]) . 在那种情况下,要确定这些对中的第一个对,将运行cmp(x=[1,2], y=[19,20])进行排序。 If the value is > 0, it assumes x is higher, if it is < 0 it considers y as higher, and if the return value is 0 it figures they are the same value. 如果值> 0,则假定x更大;如果值<0,则认为y更大;如果返回值为0,则表明它们是相同的值。

The example you chose seems a weird way to do comparisons... if the first values are equal, return the sum of the first values? 您选择的示例似乎是一种比较奇怪的方法...如果第一个值相等,则返回第一个值的总和? If they are both positive, then x will always be higher, if they are both negative, y will always be higher. 如果它们都为正,则x将始终较高,如果它们均为负,则y将始终较高。 If they aren't equal, sort solely based on the second value. 如果它们不相等,则仅根据第二个值排序。

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

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