【问题标题】:Find the maximum out of dictionary or tuple从字典或元组中找出最大值
【发布时间】:2021-12-29 09:10:19
【问题描述】:

我试图在元组和字典中找到最大值,现在我正在使用循环来做,但我真的想将代码从循环更改为列表理解,就像一个衬里代码一样。

这是我拥有的字典,我需要从中提取最大值。

student1 = {First_Name: "ABC", Last_Name: "XYZ", Age: 23}
student2 = {First_Name: "ABC", Last_Name: "XYZ", Age: 23, Address: "TYU"}
student3 = {First_Name: "ABC", Last_Name: "XYZ", Age: 23, Address: "TYUZYX"}

A = {student_One: student1, student_Two: student2, student_three: student3}

最大值应该是 student_3。

【问题讨论】:

    标签: python python-3.x dictionary tuples


    【解决方案1】:

    如果您可以发布您当前的解决方案,这样我就可以更好地为您提供帮助,但我从您的问题中了解到,您希望使用单行代码而不是循环来找到最大值.以下是实现这一目标的一些方法。

    在python中使用max函数

    如果您的字典名称是 dict,那么您可以使用以下代码查找最大值。

     max(dict, key=dict.get)
    

     dict[max(dict, key=dict.get)]
    

     max(dict)
    

    你也可以使用operator.itemgetter

    max(dict.iteritems(), key=operator.itemgetter(1))[0]
    

    有一种更快的方法可以在 Python 中从字典中获取最大值

    def keywithmaxval(d):
     # a) create a list of the dict's keys and values; 
     # b) return the key with the max value
     v=list(d.values())
     k=list(d.keys())
     return k[v.index(max(v))]
    

    您也可以使用 Lambda 运算符

    max(dict.items(), key = lambda k : dict[1])
    

    对于元组

    在元组的情况下也有很多方法,但 Python 中的 max 函数是从元组中找到最大值的最快方法。

    【讨论】:

    • 谢谢,我刚刚测试了“max(dict, key=dict.get)”,它工作正常。谢谢
    • 如果它有效,请随时接受答案。谢谢
    • 我肯定会接受这个答案。感谢您的帮助。
    • @EniGari Hasnain 所说的“接受”答案的意思是投票赞成并检查它是否已回答。
    猜你喜欢
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多