按功能对python列表进行排序 [英] Sort python list by function

查看:55
本文介绍了按功能对python列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数将一个对象作为参数并给我一个数字.我希望使用此数字作为对列表进行排序的键.

I have a function that takes an object as an argument and gives me a number. I wish to use this number as the key to sort my list.

如果要遍历列表,我会做类似的事情:

If I were to iterate over the list I would do something like:

sorted_list = []
for object in my_list_of_objects:
    i = my_number_giving_function(object)
    sorted_list.insert(i, object)

如何使用sorted来获得相同的结果,这是可取的吗?这是我想出的,但是我不知道要在"???"中添加什么?

How can I user sorted to get the same result, and is it advisable? This is what I came up with but I don't know what to put in the '???'

sorted_list = sorted(my_list_of_objects, key=my_number_giving_function(???))

推荐答案

sort(my_list_of_objects, key=my_number_giving_function)

与已排序相同,参见"Python排序方法"

这篇关于按功能对python列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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