如何用(python)列表中的顺序替换数字 [英] How to replace numbers with order in (python) list
问题描述
我有一个包含整数的列表,想要替换它们,以便以前包含最高数字的元素现在包含1,第二高数字设置为2,依此类推.
I have a list containing integers and want to replace them so that the element which previously contained the highest number now contains a 1, the second highest number set to 2, etc etc.
示例:
[5, 6, 34, 1, 9, 3]
应该产生[4, 3, 1, 6, 2, 5]
.
我个人只关心前9个最高的数字,因为我认为可能有一个简单的算法甚至一个python函数来完成这项任务?
I personally only care about the first 9 highest numbers by I thought there might be a simple algorithm or possibly even a python function to do take care of this task?
我不在乎如何处理重复项.
I don't care how duplicates are handled.
推荐答案
一种快速的方法是首先生成该元素的元组列表及其位置:
A fast way to do this is to first generate a list of tuples of the element and its position:
sort_data = [(x,i) for i,x in enumerate(data)]
接下来,我们在reverse
中对这些元素进行排序:
next we sort these elements in reverse
:
sort_data = sorted(sort_data,reverse=True)
生成的(用于您的示例输入):
which generates (for your sample input):
>>> sort_data
[(34, 2), (9, 4), (6, 1), (5, 0), (3, 5), (1, 3)]
并嵌套,我们需要填写以下元素:
and nest we need to fill in these elements like:
result = [0]*len(data)
for i,(_,idx) in enumerate(sort_data,1):
result[idx] = i
或将它们放在一起:
def obtain_rank(data):
sort_data = [(x,i) for i,x in enumerate(data)]
sort_data = sorted(sort_data,reverse=True)
result = [0]*len(data)
for i,(_,idx) in enumerate(sort_data,1):
result[idx] = i
return result
此方法适用于 O(n log n),其中 n 为data
中的元素数量.
this approach works in O(n log n) with n the number of elements in data
.
更紧凑的算法(在某种意义上说,没有用于排序的元组构成)是
A more compact algorithm (in the sense that no tuples are constructed for the sorting) is:
def obtain_rank(data):
sort_data = sorted(range(len(data)),key=lambda i:data[i],reverse=True)
result = [0]*len(data)
for i,idx in enumerate(sort_data,1):
result[idx] = i
return result
这篇关于如何用(python)列表中的顺序替换数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!