Sorting list based on values from another list?

后端 未结 15 2328
温柔的废话
温柔的废话 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 07:59

    A quick one-liner.

    list_a = [5,4,3,2,1]
    list_b = [1,1.5,1.75,2,3,3.5,3.75,4,5]
    

    Say you want list a to match list b.

    orderedList =  sorted(list_a, key=lambda x: list_b.index(x))
    

    This is helpful when needing to order a smaller list to values in larger. Assuming that the larger list contains all values in the smaller list, it can be done.

提交回复
热议问题