Skip to main content
 首页 » 编程设计

python之对列表中的元素进行排序

2025年05月04日16unruledboy

列表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)]