排序2个列表

时间:2016-01-22 19:28:28

标签: python python-2.7 sorting

我正在寻找一次对2个列表进行排序的简单方法。我需要按字母顺序对包含字符串的第一个列表进行排序,同样排序包含整数的第二个列表。列表数据是相关的(第一[1]与第二[1] ...相关)。因此,我需要为两个列表中具有相同索引的对保留相同的索引。 例如:

first = ["B","C","D","A"]   
second = [2,3,4,1]

我想这样排序:

first = ["A","B","C","D"]  
second = [1,2,3,4]

我不确定是否可以采用这种简单的方式。

3 个答案:

答案 0 :(得分:2)

你可以zip()他们,排序然后解压缩(虽然我不完全理解用例):

>>> first = ["B","C","D","A"]   
>>> second = [2,3,4,1]
>>> 
>>> zip(first, second)
[('B', 2), ('C', 3), ('D', 4), ('A', 1)]
>>> first_new, second_new = zip(*sorted(zip(first, second)))
>>> first_new
('A', 'B', 'C', 'D')
>>> second_new
(1, 2, 3, 4)

答案 1 :(得分:0)

尝试使用元组 访问wiki.python.org 例如:

>>> student_tuples = [  
        ('john', 'A', 15),  
        ('jane', 'B', 12),  
        ('dave', 'B', 10),  
]  
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age  

输出

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]  

答案 2 :(得分:0)

或者你可以使用dicts:

>>> d = {"B":2,"C":3,"D":4,"A":1}
>>> sorted(d)
['A', 'B', 'C', 'D']
>>> d["A"]
1
>>> d["C"]
3
>>> for i in sorted(d):
    print(d[i])

1
2
3
4