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

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

问题描述

说我有

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

我明白

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

会导致

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

但是这是如何工作的?

推荐答案

你传递给 key 的函数被赋予每个正在排序的项目,并返回一个键",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 的 sorted 函数中的 key 参数是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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