转换N个项目清单,以相对顺序(0-(N-1))? [英] Convert list of N items to relative ordering (0-(N-1))?

查看:193
本文介绍了转换N个项目清单,以相对顺序(0-(N-1))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有不同的项目清单:

For example if I have a list of distinct items:

L = [100,55,104,400]

相对排序可以重新

The "relative" orderings can be restated:

R = [1,0,2,3]

我不知道如何为L从一切转换成河起初我只是想减去分(L),但没有COM preSS下来,以相对顺序。

I am not sure how to convert L to R. At first I just tried subtracting min(L) from everything but that doesn't "compress" things down to relative order.

我在寻找一个有效的解决方案(而不是为O(n 2 ))。

I am looking for an efficient solution (not O(n2)).

推荐答案

您可以尝试的名单COM prehension的组合,拉链排序

You can try a combination of list comprehension, zip, and sorted:

>>> [i[1] for i in sorted(zip(L, range(4)))]
[1, 0, 2, 3]

这是O(nlogn),因为你只需要排序一次。

This is O(nlogn) since you only need to sort once.

这篇关于转换N个项目清单,以相对顺序(0-(N-1))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆