We need to open a new pit and learn the usage of sort.
a = ['a', 'b', 'c', 'd']
b = [0, 1, 2, 3]
sorted_list = [x for _, x in sorted(zip(b, a))]
Parameters
sorted(iterable, cmp=None, key=None, reverse=False)
Example of rookie tutorial:
>>>a = [5,7,6,3,4,1,2]
>>> b = sorted(a) #keep the original list
>>> a
[5, 7, 6, 3, 4, 1, 2]
>>> b
[1, 2, 3, 4, 5, 6, 7]
>>> L=[('b',2),('a',1),('c',3),('d',4)]
>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) #utilize cmp function
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> sorted(L, key=lambda x:x[1]) #utilize key
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2]) #sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(students, key=lambda s: s[2], reverse=True) #in descending order
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>>
A small detail:
The method of index extraction of list elements and sorted_Data; Is [x for _, x in sorted (zip (res, data))] equivalent? .
Not completely equivalent .
here res = [3,0,2,1] when using sorted function pairs abcd the result of sorting is bdca according to the index, rearranging should be dacb it's completely different.