【问题标题】:How to get indices of a sorted array except some values in Python?python - 如何获取排序数组的索引,但Python中的某些值除外?
【发布时间】:2019-03-17 15:15:40
【问题描述】:

我有一个数字列表:

a=[6,8,1,0,5,0]

我需要从原始列表中以升序获取索引列表,但 0 元素除外,如下所示:

index=[3,4,1,0,2,0]

【问题讨论】:

  • 原始列表的顺序重要吗?否则,您可以简单地对列表进行排序。
  • 如果列表包含重复项怎么办? a=[3,3,1,1,2,2] 的输出是什么?
  • 我认为操作想要的是排序数组的相关索引(+1),所以我认为在你的情况下应该是 index=[5, 6, 1, 2, 3, 4]

标签: python regex sorting indexing


【解决方案1】:
a = [6, 8, 1, 0, 5, 0]

sorted_positions = {x: i for i, x in enumerate(sorted(a))}
# {0: 1, 1: 2, 5: 3, 6: 4, 8: 5}

indices = [sorted_positions[x] for x in a]
# [4, 5, 2, 1, 3, 1]

zeroes = a.count(0)
# 2

answer = [
    0 if x == 0
    else i - zeroes + 1
    for i, x in zip(indices, a)
]
# [3, 4, 1, 0, 2, 0]

如果您不认识语法,要搜索的术语:列表推导、字典推导和 python 三元运算符。

对于a=[3,3,1,1,2,2] 的情况,这给出了[6, 6, 2, 2, 4, 4]

【讨论】:

    【解决方案2】:

    使用 numpy 的 argsort 为这个问题带来了一定的优雅

    import numpy as np
    a=[6,8,1,0,5,0]
    #create a numpy array
    temp = np.array(a) 
    #assign non zero values in array with correct argsort indices.
    temp[temp != 0] = np.argsort(temp[temp != 0]) + 1 
    print(temp)
    [3 4 1 0 2 0]
    

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 2020-05-21
      • 2011-09-19
      • 1970-01-01
      • 2021-06-03
      • 2016-10-20
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多