[英]Get the index in order of values from max to min without sorting the output index list and amend another list as well
I am trying to get the indices of the values in the array from maximum to minimum without sorting the indices positions. 我试图获取数组中值的索引从最大值到最小值,而不对索引位置进行排序。 Here is the current code I have
这是我目前的代码
s = [20, 30, 45, 14, 59]
ans = sorted(range(len(s)), key=lambda k: s[k], reverse=True)
print ans
but I am getting the output as [4, 2, 1, 0, 3]
which is based on sorting. 但是我得到的输出是
[4, 2, 1, 0, 3]
,它是基于排序的。 I don't want the sorted list of indexes instead I want them in same position. 我不需要索引的排序列表,而是希望它们位于相同的位置。 Output should be
[3, 2, 1, 4, 0]
. 输出应为
[3, 2, 1, 4, 0]
。 Is there any way to achieve this? 有什么办法可以做到这一点?
For 2D: Now if there is another array (only with -1, 0, 1) associated with the first array sv = [(1,0), (-1,1), (-1,0), (0,-1), (1,1)]
. 对于2D:现在,如果存在与第一个数组相关联的另一个数组(仅包含-1、0、1),则
sv = [(1,0), (-1,1), (-1,0), (0,-1), (1,1)]
。 Here each value in sv is indexed and bind to same output array [3, 2, 1, 4, 0]
. 在这里,sv中的每个值都被索引并绑定到相同的输出数组
[3, 2, 1, 4, 0]
。 Now based on certain condition say 现在根据一定条件说
for i in s if any val[i] < max(val[i])*25/100
value will be removed from s as well as sv and also its indexing. 值将从s和sv及其索引中删除。 So in above case new s, new sv and new indexing output will be
因此,在上述情况下,new,new sv和new indexing输出将是
s = [20, 30, 45, 59]
indexing = [3, 2, 1, 0]
sv = [(1,0), (-1,1), (-1,0), (1,1)]
You can use a dict that maps each list item to its sorted index: 您可以使用将每个列表项映射到其排序索引的字典:
mapping = {k: i for i, k in enumerate(sorted(s, reverse=True))}
print([mapping[i] for i in s])
This outputs: 输出:
[3, 2, 1, 4, 0]
s = [20, 30, 45, 14, 59]
ss = sorted(s,reverse=True)
print([s.index(i) for i in ss]) ## gives [4, 2, 1, 0, 3]
print([ss.index(i) for i in s]) ## gives [3, 2, 1, 4, 0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.