如何返回排序列表的索引? [英] how to return index of a sorted list?

查看:59
本文介绍了如何返回排序列表的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对一个列表进行排序,然后返回一个列表,其中包含列表中已排序项目的索引.比如我要排序的列表是[2,3,1,4,5],我需要[2,0,1,3,4]被退回.

这个问题是在字节上发布的,但我想我会在这里重新发布.http://bytes.com/topic/python/answers/44513-排序列表然后返回索引排序项

我特别需要根据对象的属性对对象列表进行排序.然后我需要重新排序相应的列表以匹配新排序列表的顺序.

有什么好的办法吗?

解决方案

您可以改用 python 排序函数的 key 参数对索引数组进行排序.

<预><代码>>>>s = [2, 3, 1, 4, 5, 3]>>>排序(范围(len(s)),键= lambda k:s [k])[2, 0, 1, 5, 3, 4]>>>

I need to sort a list and then return a list with the index of the sorted items in the list. For example, if the list I want to sort is [2,3,1,4,5], I need [2,0,1,3,4] to be returned.

This question was posted on bytes, but I thought I would repost it here. http://bytes.com/topic/python/answers/44513-sorting-list-then-return-index-sorted-item

My specific need to sort a list of objects based on a property of the objects. I then need to re-order a corresponding list to match the order of the newly sorted list.

Is there a good way to do this?

解决方案

You can use the python sorting functions' key parameter to sort the index array instead.

>>> s = [2, 3, 1, 4, 5, 3]
>>> sorted(range(len(s)), key=lambda k: s[k])
[2, 0, 1, 5, 3, 4]
>>> 

这篇关于如何返回排序列表的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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