【问题标题】:How do I get the indexes from the biggest to smallest number in a list?如何从列表中的最大数字到最小数字获取索引?
【发布时间】: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


    【解决方案1】:

    我对 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] 无关紧要,因为这些索引引用相同的值。

    【讨论】:

    • 如果列表中有重复值将不起作用。此外,性能是 O(n²),其中排序应该是 O(n log(n))
    • 我应该怎么做?什么时候有重复值?
    • @Andreas 你有什么想法吗?
    • @AntonisAsonitis 我已经给了my answer,你已经接受了。
    • @AntonisAsonitis:我添加了一个解决方案来考虑重复值。
    【解决方案2】:

    按索引升序构建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());
    

    【讨论】:

    • OP 写道:I am coding a little project in Python,这看起来不像 python?
    • hmmm,它是 JAVA,当您将输入更改为 20, 10, 24, 26, 22, 10 时,您的代码的输出是 [3, 2, 4, 0, 1, 5],实际上我的 python 东西说 [3, 2, 4, 0, 1, 1],仍然是我的问题如何做到这一点在 python 中......(但总有一天我会解决这个问题的!)
    • 你的答案是 Java,而不是 Python!
    【解决方案3】:

    接受的答案不在 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]
    

    它处理重复值的索引,而且速度非常快。它需要导入,但如果您正在处理大型数据集,那么它可能会具有您需要的其他功能,并且总体上会节省时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2016-02-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多