Sorting list based on values from another list?

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

    Zip the two lists together, sort it, then take the parts you want:

    >>> yx = zip(Y, X)
    >>> yx
    [(0, 'a'), (1, 'b'), (1, 'c'), (0, 'd'), (1, 'e'), (2, 'f'), (2, 'g'), (0, 'h'), (1, 'i')]
    >>> yx.sort()
    >>> yx
    [(0, 'a'), (0, 'd'), (0, 'h'), (1, 'b'), (1, 'c'), (1, 'e'), (1, 'i'), (2, 'f'), (2, 'g')]
    >>> x_sorted = [x for y, x in yx]
    >>> x_sorted
    ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
    

    Combine these together to get:

    [x for y, x in sorted(zip(Y, X))]
    

提交回复
热议问题