繁体   English   中英

按从最大值到最小值的值顺序获取索引,而无需对输出索引列表进行排序,也可以修改另一个列表

[英]Get the index in order of values from max to min without sorting the output index list and amend another list as well

我试图获取数组中值的索引从最大值到最小值,而不对索引位置进行排序。 这是我目前的代码

s = [20, 30, 45, 14, 59]
ans = sorted(range(len(s)), key=lambda k: s[k], reverse=True)
print ans

但是我得到的输出是[4, 2, 1, 0, 3] ,它是基于排序的。 我不需要索引的排序列表,而是希望它们位于相同的位置。 输出应为[3, 2, 1, 4, 0] 有什么办法可以做到这一点?

对于2D:现在,如果存在与第一个数组相关联的另一个数组(仅包含-1、0、1),则sv = [(1,0), (-1,1), (-1,0), (0,-1), (1,1)] 在这里,sv中的每个值都被索引并绑定到相同的输出数组[3, 2, 1, 4, 0] 现在根据一定条件说

for i in s if any val[i] < max(val[i])*25/100

值将从s和sv及其索引中删除。 因此,在上述情况下,new,new sv和new indexing输出将是

s = [20, 30, 45, 59]
indexing = [3, 2, 1, 0]
sv = [(1,0), (-1,1), (-1,0), (1,1)]

您可以使用将每个列表项映射到其排序索引的字典:

mapping = {k: i for i, k in enumerate(sorted(s, reverse=True))}
print([mapping[i] for i in s])

输出:

[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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM