Python初学者-使用Lambda函数对元组进行排序 [英] Python beginner - Sorting tuples using lambda functions

查看:562
本文介绍了Python初学者-使用Lambda函数对元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关Python的教程简介,并且坚持理解一段代码.这是来自本教程的4.7.5节.

I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.

pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs

这段代码返回

[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

因此在第一行中,它定义了具有不同元组列表的对.我明白了. 第二行是我完全被抛弃的地方,为了弄清楚正在发生的事情,我做了很多的弄乱.

So in line one, it defines pairs with a list of different tuples. I get that. Line two is where I'm completely thrown off and I've done quite a bit of messing around with it to try to understand what's happening.

我发现sort()正在将内置函数应用于变量对,并且大概是按照我给出的指令对它进行排序.

I've found that sort() is applying a built-in function to the variable pairs, and presumably it is sorting it per the instructions I'm giving it.

sort()函数需要一个键,并且必须使用一个函数来定义键,因此必须使用lambda.我认为所有这些都是正确的,但是我可能离这里很远.

The sort() function requires a key, and key has to be defined using a function, hence the use of lambda. I think all of this is correct, but I may be way off here.

Lambda在冒号左侧定义了一个新参数"pair",在右侧是用于定义lambda函数的返回值的计算.

Lambda defines a new parameter, "pair" on the left side of the colon, and on the right side is the calculation to define the return value of the lambda function.

那是我被抛弃的地方. "pair [1]"是做什么的?它对结肠左侧的对"有什么影响?

That's where I'm thrown off. What does "pair[1]" do? What is its affect on the "pair" on the left side of the colon?

它返回什么值?我似乎无法像这样对它进行编码以外返回任何类型的值.

What value does it return? I can't seem to get it to return any sort of value outside of coding it just like this.

我猜测它以某种方式指向一个特定的元组,并基于重新定位对该元组进行排序,但是我不确定其背后的逻辑.

I'm guessing that it somehow points to a specific tuple and sorts it based on repositioning that, but I'm not sure of the logic behind that.

有人可以帮我解释一下吗?谢谢.

Can anyone explain this for me? Thank you.

推荐答案

有时,当开始使用lambda时,显式地写出函数会更容易.您的lambda函数等效于:

Sometimes when starting to work with lambda, it's easier to write out the function explicitly. Your lambda function is equivalent to:

def sort_key(pair):
    return pair[1]

如果我们想更详细些,我们可以解开配对以使其更加明显:

If we want to be more verbose, we can unpack pair to make it even more obvious:

def sort_key(pair):
    int_value, string_value = pair
    return string_value

由于list.sort根据key函数的返回值(如果存在)对项目进行排序,现在我们看到它正在按元组的 string值对元组进行排序.由于字符串按字典顺序排序,因此"four""one"之前(请考虑字母顺序).

Because list.sort orders the items based on the return value of the key function (if present), now we see that it is sorting the tuples by their string value. Since strings sort lexicographically, "four" comes before "one" (think alphabetical order).

这篇关于Python初学者-使用Lambda函数对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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