难以理解lambda函数 [英] Difficulty understanding lambda function in sort

查看:98
本文介绍了难以理解lambda函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我定义了一个列表lol的列表:

Let's say I define a list of lists lol:

lol = [['malasia', 0.02, 56.3], ['chile', 0.03, 34.9],
       ['hungria', 0.01, 45.9], ['ahumada', 0.001, 1]]

然后

lol.sort(lambda x, y: cmp(y[2], x[2]))

按每个子列表的最后一个元素对lol进行排序...

orders lol by the last element of each sublist...

我只是想了解sort的组成部分:

I'm just trying to understand the component parts of the sort:

  • cmp(y,x)与数字进行比较,并返回-1(y减去x),0(x等于y)或1(y更大的x).

  • cmp(y,x) compares to numbers and returns -1 (y less x), 0 (x equals y), or 1 (y bigger x).

lambda是否在每个列表的最后一个元素上定义函数? 那里面的lambda怎么样?我很困惑-有人可以解释lambda函数的作用吗?

lambda is defining a function over the last elements of each list? Then lambda inside a sort? I'm confused- could anybody explain what the lambda function does?

推荐答案

使用sortkey参数实际上更好,而cmp有点过时.

This is actually better done using the key argument to sort, cmp is somewhat outdated.

例如:

lol.sort(key=lambda x: x[2])

(您也可以使用x [-1]表示列表的最后一个元素)

(you could also use x[-1] to mean the last element of the list)

您正在创建lambda并将其传递给sort函数.您也可以这样写:

You are creating the lambda and passing it into the sort function. You could also write it like this:

get_third_element = lambda x: x[2]
lol.sort(key=get_third_element)

或者使其更易于理解:

def get_third_element(x):
    return x[2]

lol.sort(key=get_third_element)

没有理由不能将一个函数作为参数传递给另一个函数!

There's no reason you can't pass a function into another function as an argument!

这篇关于难以理解lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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