python排序返回索引_如何返回排序列表的索引?

如果需要排序列表和索引列表,可以执行以下操作:L = [2,3,1,4,5]

from operator import itemgetter

indices, L_sorted = zip(*sorted(enumerate(L), key=itemgetter(1)))

list(L_sorted)

>>> [1, 2, 3, 4, 5]

list(indices)

>>> [2, 0, 1, 3, 4]

或者,对于Python<2.4(没有itemgetter或sorted):temp = [(v,i) for i,v in enumerate(L)]

temp.sort

indices, L_sorted = zip(*temp)

p.s.zip(*iterable)习惯用法反转zip进程(unzip)。

更新:

为了满足您的具体要求:"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."

那是一个冗长的工作方式。通过将两个列表压缩在一起,然后使用object属性作为排序键进行排序(然后在之后解压缩),您可以通过一次排序来实现这一点。combined = zip(obj_list, secondary_list)

zipped_sorted = sorted(combined, key=lambda x: x[0].some_obj_attribute)

obj_list, secondary_list = map(list, zip(*zipped_sorted))

下面是一个简单的例子,使用字符串来表示对象。这里我们使用字符串的长度作为排序的键str_list = ["banana", "apple", "nom", "Eeeeeeeeeeek"]

sec_list = [0.123423, 9.231, 23, 10.11001]

temp = sorted(zip(str_list, sec_list), key=lambda x: len(x[0]))

str_list, sec_list = map(list, zip(*temp))

str_list

>>> ['nom', 'apple', 'banana', 'Eeeeeeeeeeek']

sec_list

>>> [23, 9.231, 0.123423, 10.11001]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值