假设我有一个列表 [10, 5, 7],我想将其缩减为表示相对顺序的内容 [3, 1, 2]。我不知道如何在Python中进行转换。
假设我有一个列表 [10, 5, 7],我想将其缩减为表示相对顺序的内容 [3, 1, 2]。我不知道如何在Python中进行转换。
lst = [10, 5, 7]
std = sorted(lst)
[std.index(e)+1 for e in lst]
=> [3, 1, 2]
start = [10, 5, 7]
排序它
step1 = sorted(start) #if you have duplicates, sorted(set(start)) to uniquify
lookup = {v:i for i,v in enumerate(step1,1)}
[lookup[x] for x in start]
Out[9]: [3, 1, 2]
index
搜索的O(n**2)解决方案。时间记录:test = [randrange(0,10000) for _ in range(10000)]
def f():
std = sorted(test)
return [std.index(e)+1 for e in test]
def g():
step1 = sorted(test)
lookup = {v:i for i,v in enumerate(step1,1)}
return [lookup[x] for x in test]
%timeit f()
1 loops, best of 3: 1.17 s per loop
%timeit g()
100 loops, best of 3: 6.58 ms per loop
a = [10,5,7]
b = sorted(a)
newList = []
for i in a:
newList.append(b.index(i))
print newList
In [29]: L=[10,5,7]
In [30]: %paste
inds = {}
for v,k in enumerate(sorted(L),1):
if k not in inds:
inds[k] = []
inds[k].append(v)
answer = [inds[k].pop() for k in L]
## -- End pasted text --
In [31]: answer
Out[31]: [3, 1, 2]