如果需要排序列表和索引列表,可以执行以下操作: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]