python怎么替换列表中的数字,如何用(python)列表中的顺序替换数字

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.

Example:

[5, 6, 34, 1, 9, 3] should yield [4, 3, 1, 6, 2, 5].

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?

Edit: 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)]

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

Or putting it together:

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值