【问题标题】:Sort python list by order of another list AND retrieve old index按另一个列表的顺序对python列表进行排序并检索旧索引
【发布时间】:2019-09-25 00:06:23
【问题描述】:

试图检索排序列表“秒”的索引。 "second" 包含与 "first" 相同的值,并将被重新排序以成为与 "first" 相同的顺序。我正在寻找一个索引列表“d”,其中包含旧“第二个”的重新排序索引。

尝试使用 zip 或枚举检索“d”,但失败了。

first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
second=[(22.354,0.656,0.664),(33.654,33.546,31.131),(11.373,0.354,6.154)]

second=sorted(second,key=first.index)

print(first)
print(second)
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]

这里的“第二”与“第一”的顺序相同。凉爽的。 但是如何从“second”检索重新排序的索引列表“d”?

我试过这样: d = [i[0] for i in sorted(enumerate(second), key=first.index)]

在本例中,“d”应变为 [2,0,1]

这种类型的键以某种方式阻止了检索旧索引的可能性。有什么推荐吗?

【问题讨论】:

    标签: python list sorting indexing


    【解决方案1】:

    这是一种方法。

    例如:

    first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
    second=[(22.354,0.656,0.664),(33.654,33.546,31.131),(11.373,0.354,6.154)]
    
    temp = sorted(second,key=first.index)            #Sorted List. 
    d = list(map(lambda x: second.index(x), temp))   #Fetch index from temp
    
    print(first)
    print(temp)
    print(d)
    

    输出:

    [(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
    [(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
    [2, 0, 1]
    

    【讨论】:

    • 以这种方式获取索引很好,这就是诀窍。谢谢。
    【解决方案2】:

    如果我正确理解了您的问题,您可以使用 numpy argsort 并绕过“第二”的需要。

    这是一个代码 sn-p。

    from pprint import pprint
    import numpy
    
    def main():
        first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
        index_array= (numpy.argsort(first))
        for i in index_array:
            pprint(i.tolist())
    
    if __name__== "__main__":
        main()
    

    输出:

    [1, 2, 0]
    [1, 2, 0]
    [2, 1, 0]
    

    请记住 index_array 包含原始列表中的索引,因此如果您按照应用于原始列表的顺序使用它们,则列表将被排序。

    【讨论】:

      【解决方案3】:

      您可以再次使用index 来获取原始列表中的索引,但是(a)如果有重复的元素,这可能会失败,并且(b)这有两次 O(n²)。相反,我建议使用enumerate(first) 将第一个元素映射到它们的索引,然后使用sorting 来自enumerate(second)(index, element) 对,使用该映射中的索引作为键,从@ 获取排序索引987654326@.

      >>> ind = {x: i for i, x in enumerate(first)}
      >>> [i for i, x in sorted(enumerate(second), key=lambda t: ind[t[1]])]
      [2, 0, 1]
      

      【讨论】:

        【解决方案4】:

        这会有所帮助:

        sorted(range(len(second)),key=second.__getitem__)
        

        同时获取项目和索引

        sorted_indices, sorted_items = zip(*sorted([(i,e) for i,e in enumerate(second)], key=lambda x:x[1]))
        

        【讨论】:

        • 谢谢,但不是我要找的,因为这段代码是简单的排序,没有考虑“第一”的顺序。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-09-07
        • 2011-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-30
        相关资源
        最近更新 更多