【问题标题】:Sort one list according to the order of another list [duplicate]根据另一个列表的顺序对一个列表进行排序[重复]
【发布时间】:2018-09-15 03:41:22
【问题描述】:

请参阅以下 2 个列表:

如果我将猫及其年龄附加到两个不同的列表中,我如何对其进行排序,以便在打印最老猫的年龄时,也打印卢克,而在打印最小猫的年龄时,罗尼也被打印出来。

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

我该怎么做?

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    你可以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
    

    【讨论】:

    • 如果我将列表缩减为 cat = ["ronny"] 和 age = ["5"] 我怎么还能使用它但不会遇到超出范围的错误
    • @LucasEng 这段代码不会对更新的列表值产生索引错误(在 python 3.5 中尝试过)。您确定超出范围错误是由这段代码产生的,而不是在其他地方产生的吗?
    猜你喜欢
    • 2018-01-03
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-17
    • 2013-09-12
    • 2023-02-08
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多