Sorting list based on values from another list?

后端 未结 15 2327
温柔的废话
温柔的废话 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:13

    Here is Whatangs answer if you want to get both sorted lists (python3).

    X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
    Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]
    
    Zx, Zy = zip(*[(x, y) for x, y in sorted(zip(Y, X))])
    
    print(list(Zx))  # [0, 0, 0, 1, 1, 1, 1, 2, 2]
    print(list(Zy))  # ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
    

    Just remember Zx and Zy are tuples. I am also wandering if there is a better way to do that.

    Warning: If you run it with empty lists it crashes.

提交回复
热议问题