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