[英]How do I get the indexes from the biggest to smallest number in a list?
I am coding a little project in Python:我正在用 Python 编写一个小项目:
I want to get the indexes (in a list) from the highest to smallest number in the following list:我想获取以下列表中从最高到最小的索引(在列表中):
list = [20, 30, 24, 26, 22, 10]
The outcome should be:结果应该是:
index_list = [1, 3, 2, 4, 0, 5]
Anyone has an idea of how I could do that?任何人都知道我该怎么做? Thanks in advance.提前致谢。
Build the index_list
in ascending index order, then call sort()
with a Comparator
that sorts descending by the value in the list
at the given index.以升序索引顺序构建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);
Output输出
[1, 3, 2, 4, 0, 5]
Or you can do it in one statement using streams, same result:或者您可以使用流在一个语句中完成,结果相同:
List<Integer> index = IntStream.range(0, list.size()).boxed()
.sorted(Comparator.comparing(list::get).reversed())
.collect(Collectors.toList());
I am pretty new to programming in python, but this seems to work:我对 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)
output:输出:
[1, 3, 2, 4, 0, 5]
Because above will produce incorrect values it there are duplicates, see next:因为上面会产生不正确的值,所以有重复,请参见下一个:
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)
output:输出:
[20, 10, 24, 26, 22, 10]
[3, 2, 4, 0, 5, 1]
It should not matter if output is [3, 2, 4, 0, 5, 1]
or [3, 2, 4, 0, 1, 5]
because those indexes refer to the same values.输出是[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.