python的排序函数中的关键参数如何工作? [英] How does the key argument in python's sorted function work?

查看:107
本文介绍了python的排序函数中的关键参数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

votes = {'Charlie': 20, 'Able': 10, 'Baker': 20, 'Dog': 15}

我明白

print(sorted(votes.items(), key = lambda x: x[1]))

将导致


[('Able',10),(' ,15),('Baker',20),('Charlie',20)]`

[('Able', 10), ('Dog', 15), ('Baker', 20), ('Charlie', 20)]`

但这是如何工作的?

推荐答案

您传递给键的功能正在排序的项目,并返回一个键,Python可以排序。所以,如果你想通过字符串的反向排序字符串列表,你可以这样做:

The function you pass in to key is given each of the items that are being sorted, and returns a "key" that Python can sort by. So, if you want to sort a list of strings by the reverse of the string, you could do this:

list_of_strings.sort(key=lambda s: s[::-1])

这允许您指定每个项目排序的值,而无需更改项目。这样一来,您就不必编制一个反转字符串列表,排序,然后将其反转。

This lets you specify the value each item is sorted by, without having to change the item. That way, you don't have to build a list of reversed strings, sort that, then reverse them back.

# DON'T do this

data = ['abc', 'def', 'ghi', 'jkl']
reversed_data = [s[::-1] for s in data]
reversed_data.sort()
data = [s[::-1] for s in reversed_data]

# Do this

data.sort(key=lambda s: s[::-1])

在你的情况下,代码是通过元组中的第二个项排序每个项目,而通常它最初将按元组中的第一个项目排序,然后与第二个项目断开关系。

In your case, the code is sorting each item by the second item in the tuple, whereas normally it would initially sort by the first item in the tuple, then break ties with the second item.

这篇关于python的排序函数中的关键参数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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