Sorting list based on values from another list?

后端 未结 15 2326
温柔的废话
温柔的废话 2020-11-21 07:14

I have a list of strings like this:

X = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\"]
Y = [ 0,   1,   1,   0,   1,   2,   2,   0,   1 ]
         


        
15条回答
  •  时光说笑
    2020-11-21 08:01

    I like having a list of sorted indices. That way, I can sort any list in the same order as the source list. Once you have a list of sorted indices, a simple list comprehension will do the trick:

    X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
    Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]
    
    sorted_y_idx_list = sorted(range(len(Y)),key=lambda x:Y[x])
    Xs = [X[i] for i in sorted_y_idx_list ]
    
    print( "Xs:", Xs )
    # prints: Xs: ["a", "d", "h", "b", "c", "e", "i", "f", "g"]
    

    Note that the sorted index list can also be gotten using numpy.argsort().

提交回复
热议问题