我想要一个函数返回一个列表,这样,给定一个"混乱"列表l,每个元素是相应元素的索引l,如果l被排序.(我没有想到一种不太复杂的说法,对不起.)
例子
f([3,1,2]) = [2,0,1]
f([3,1,2,2,3])= [3,0,1,2,4],因为输入已排序[1,2,2,3,3].
(这对某些统计数据计算很有用.)
我想出了一种方法来做这个功能,但这是python - 似乎应该有一个单行来做这个,或者至少是一个更清洁,更清晰的方式.
def getIndiciesInSorted(l):
sortedL = sorted(l)
outputList = []
for num in l:
sortedIndex = sortedL.index(num)
outputList.append(sortedIndex)
sortedL[sortedIndex] = None
return outputList
l=[3,1,2,2,3]
print getIndiciesInSorted(l)
Run Code Online (Sandbox Code Playgroud)
那么,我怎样才能更简洁地写出来呢?有清晰易读的清单解决方案吗?
def argsort(seq):
# http://stackoverflow.com/questions/3382352/3382369#3382369
# http://stackoverflow.com/questions/3071415/3071441#3071441
'''
>>> seq=[1,3,0,4,2]
>>> index=argsort(seq)
[2, 0, 4, 1, 3]
Given seq and the index, you can construct the sorted seq:
>>> sorted_seq=[seq[x] for x in index]
>>> assert sorted_seq == sorted(seq)
Given the sorted seq and the index, you can reconstruct seq:
>>> assert [sorted_seq[x] for x in argsort(index)] == seq
'''
return sorted(range(len(seq)), key=seq.__getitem__)
def f(seq):
idx = argsort(seq)
return argsort(idx)
print(f([3,1,2]))
# [2, 0, 1]
print(f([3,1,2,2,3]))
# [3, 0, 1, 2, 4]
Run Code Online (Sandbox Code Playgroud)
请注意,nightcracker的功能更快:
def get_sorted_indices(l):
sorted_positions = sorted(range(len(l)), key=l.__getitem__)
result = [None for _ in range(len(l))]
for new_index, old_index in enumerate(sorted_positions):
result[old_index] = new_index
return result
Run Code Online (Sandbox Code Playgroud)
长列表的差异可能很大:
In [83]: import random
In [98]: l = [random.randrange(100) for _ in range(10000)]
In [104]: timeit get_sorted_indices(l)
100 loops, best of 3: 4.73 ms per loop
In [105]: timeit f(l)
100 loops, best of 3: 6.64 ms per loop
Run Code Online (Sandbox Code Playgroud)