列表A和列表B具有相应的元素:

A = ['a','c','b']
B = [5,7,9]


如何对A中的元素进行排序(如下所示进行A_sorted),而B中的值不变(如下所示进行B_sorted)?

A_sorted = A.sort()

A_sorted = ['a','b','c']
B_sorted = [5,9,7]

最佳答案

A = ['a','c','b']
B = [5,7,4]

A_sorted, B_sorted = zip(*sorted(zip(A, B))


结果:

>>> A_sorted
('a', 'b', 'c')
>>> B_sorted
(5, 4, 7)


说明:

>>> step_1 = zip(A,B) # creates list of tuples using
                      # two original lists
                      # tuples will allow us to keep correspondence
                      # between A and B
>>> step_1
[('a', 5), ('c', 7), ('b', 4)]
>>> step_2 = sorted(step_1) # key step: the tuples are sorted by
                            # the first value.
>>> step_2
[('a', 5), ('b', 4), ('c', 7)]
>>> step_3 = zip(*step_2)   # This is just a trick to get back the original
                            # "lists", however they are actually tuples
>>> step_3
[('a', 'b', 'c'), (5, 4, 7)]

10-07 16:30