【发布时间】:2020-04-28 21:51:33
【问题描述】:
我正在用 Python 编写一个小项目:
我想获取以下列表中从最高到最小的索引(在列表中):
list = [20, 30, 24, 26, 22, 10]
结果应该是:
index_list = [1, 3, 2, 4, 0, 5]
有人知道我该怎么做吗? 提前致谢。
【问题讨论】:
标签: python list indexing max min
我正在用 Python 编写一个小项目:
我想获取以下列表中从最高到最小的索引(在列表中):
list = [20, 30, 24, 26, 22, 10]
结果应该是:
index_list = [1, 3, 2, 4, 0, 5]
有人知道我该怎么做吗? 提前致谢。
【问题讨论】:
标签: python list indexing max min
我对 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] 无关紧要,因为这些索引引用相同的值。
【讨论】:
按索引升序构建index_list,然后调用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());
【讨论】:
I am coding a little project in Python,这看起来不像 python?
20, 10, 24, 26, 22, 10 时,您的代码的输出是 [3, 2, 4, 0, 1, 5],实际上我的 python 东西说 [3, 2, 4, 0, 1, 1],仍然是我的问题如何做到这一点在 python 中......(但总有一天我会解决这个问题的!)
接受的答案不在 Python 中,而另一个答案需要几行代码,而且速度不如更大数据集的速度,所以我想我会把帽子扔在戒指上:
import numpy as np
list = [20, 30, 24, 26, 22, 10]
index_list = np.array(list).argsort().tolist()[::-1]
输出确实是:
index_list = [1, 3, 2, 4, 0, 5]
它处理重复值的索引,而且速度非常快。它需要导入,但如果您正在处理大型数据集,那么它可能会具有您需要的其他功能,并且总体上会节省时间。
【讨论】: