繁体   English   中英

如何获取列表中从最大到最小的索引?

[英]How do I get the indexes from the biggest to smallest number in a list?

我正在用 Python 编写一个小项目:

我想获取以下列表中从最高到最小的索引(在列表中):

list = [20, 30, 24, 26, 22, 10]

结果应该是:

index_list = [1, 3, 2, 4, 0, 5]

任何人都知道我该怎么做? 提前致谢。

以升序索引顺序构建index_list ,然后使用Comparator调用sort() ,该Comparator按给定索引处的list中的值进行降序排序。

List<Integer> list = Arrays.asList(20, 30, 24, 26, 22, 10);

List<Integer> index = new ArrayList<>(list.size());
for (int i = 0; i < list.size(); i++)
    index.add(i);
index.sort(Comparator.comparing(list::get).reversed());

System.out.println(index);

输出

[1, 3, 2, 4, 0, 5]

或者您可以使用流在一个语句中完成,结果相同:

List<Integer> index = IntStream.range(0, list.size()).boxed()
                               .sorted(Comparator.comparing(list::get).reversed())
                               .collect(Collectors.toList());

我对 python 编程很陌生,但这似乎有效:

list = [20, 30, 24, 26, 22, 10]
list_sorted = list.copy()
list_sorted.sort()

list_index = []
for x in list_sorted:
    list_index.insert(0,list.index(x))

print(list_index)

输出:

[1, 3, 2, 4, 0, 5]

因为上面会产生不正确的值,所以有重复,请参见下一个:

list = [20, 10, 24, 26, 22, 10]
list_tmp = list.copy()
list_sorted = list.copy()
list_sorted.sort()

list_index = []
for x in list_sorted:
    list_index.insert(0,list_tmp.index(x))
    list_tmp[list_tmp.index(x)] = -1

print(list)
print(list_index)

输出:

[20, 10, 24, 26, 22, 10]
[3, 2, 4, 0, 5, 1]

输出是[3, 2, 4, 0, 5, 1]还是[3, 2, 4, 0, 1, 5]应该无关紧要[3, 2, 4, 0, 1, 5]因为这些索引引用相同的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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