[英]Sorting 2 lists
I am looking for simple way to sort 2 lists at once. 我正在寻找一次对2个列表进行排序的简单方法。 I need to sort first list containing strings by alphabet a same way sort second list containing integers.
我需要用字母对包含字符串的第一列表进行排序,方法与对包含整数的第二列表进行排序的方法相同。 Data of lists are related (first[1] is related with second[1] ... ).
列表的数据相关(first [1]与second [1] ...相关)。 So I need to keep same index for the pair with same index from both lists.
因此,我需要为两个列表中具有相同索引的对保留相同的索引。 For example:
例如:
first = ["B","C","D","A"]
second = [2,3,4,1]
I would like to sort it like this: 我想这样排序:
first = ["A","B","C","D"]
second = [1,2,3,4]
I am not sure if is it even possible to do that simple way. 我不知道是否有可能这样做。
You can zip()
them, sort and then unzip (though I don't fully understand the use case): 您可以对它们进行
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)
try to using tuple visit wiki.python.org ex: 尝试使用元组访问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
output 输出
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
or you could use 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.