根据另一个列表的顺序对一个列表进行排序

时间:2018-04-05 10:37:39

标签: python python-3.x list

请参阅以下2列表:

如果我将猫及其年龄附加到两个不同的清单上,我该如何对它进行分类,以便在打印出最古老的猫的年龄时,也会打印出Luke,而当打印最年轻的猫的年龄时,Ronny也印了。

cats = ["ronny", "brodie", "fraise", "luke"]
age = [5, 6, 7, 11]

age.sort()
print("The age of the oldest cat is {}. This cat is {}".format(age[-1], 
cats[THE OLDEST CAT]))
print("The age of the youngest cat is {}. This cat is {}".format(age[0], 
cats[THE YOUNGEST CAT]))

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您可以zip这两个列表,然后对它们应用sorted,以便将年龄相同的猫放在一个元组中。如下所示:

In [60]: cats = ["ronny", "brodie", "fraise", "luke"]
    ...: age = [5, 6, 7, 11]
    ...: cats_by_age = sorted(zip(age, cats))
    ...: 
    ...: print("The age of the oldest cat is {}. This cat is {}".format(*cats_by_age[-1]))
    ...: print("The age of the youngest cat is {}. This cat is {}".format(*cats_by_age[0]))
    ...: 
The age of the oldest cat is 11. This cat is luke
The age of the youngest cat is 5. This cat is ronny