Sorting list based on values from another list?

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

    You can create a pandas Series, using the primary list as data and the other list as index, and then just sort by the index:

    import pandas as pd
    pd.Series(data=X,index=Y).sort_index().tolist()
    

    output:

    ['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
    
    0 讨论(0)
  • 2020-11-21 07:54

    zip, sort by the second column, return the first column.

    zip(*sorted(zip(X,Y), key=operator.itemgetter(1)))[0]
    
    0 讨论(0)
  • 2020-11-21 07:56

    I actually came here looking to sort a list by a list where the values matched.

    list_a = ['foo', 'bar', 'baz']
    list_b = ['baz', 'bar', 'foo']
    sorted(list_b, key=lambda x: list_a.index(x))
    # ['foo', 'bar', 'baz']
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 08:01

    Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution:

    people = ['Jim', 'Pam', 'Micheal', 'Dwight']
    ages = [27, 25, 4, 9]
    
    import numpy
    people = numpy.array(people)
    ages = numpy.array(ages)
    inds = ages.argsort()
    sortedPeople = people[inds]
    

    I found it here: http://scienceoss.com/sort-one-list-by-another-list/

    0 讨论(0)
  • 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().

    0 讨论(0)
提交回复
热议问题