【问题标题】:Getting the max and min from a dictionary without using max() and min()不使用 max() 和 min() 从字典中获取最大值和最小值
【发布时间】:2021-02-12 10:04:30
【问题描述】:

我有一个包含两个值(id 和数量)的字典:

dict={5: [379], 11: [396], 6: [480], 19: [443]}

我想在不使用 max 和 min 函数的情况下从字典中找到具有最大和最小数量的 id。

所以想要的输出是:

max=6
min=5

【问题讨论】:

  • 请分享您的代码。
  • 你的值是列表还是整数?
  • 请解释为什么不min() 和max()? sorted() 怎么样?
  • list(map(lambda x: x[0], sorted(d.items(), key=lambda x: x[1])[::len(d)-1]))

标签: python dictionary max min


【解决方案1】:

python中的字典是可迭代的,即可以逐项遍历。

在这种情况下,你可以做类似的事情

for key in dict_a:
    #do something here to find the min and max
    print(key)

【讨论】:

    【解决方案2】:

    你可以用 for 循环来计算它:

    input = {5: 379, 11: 396, 6: 480, 19: 443}
    
    keys = input.keys()
    largest_key = keys[0]
    
    for key in keys:
        if input[key] > input[largest_key]:
            largest_key = key
    
    print(largest_key)
    

    如果您的值是列表,您需要选择用于比较列表的索引。在下面的代码中,我硬编码为零。如果您想遍历列表并在那里找到最大值,那将只是另一个嵌套循环。

    input = {5: [379], 11: [396], 6: [480], 19: [443]}
    
    keys = input.keys()
    largest_key = keys[0]
    
    for key in keys:
        if input[key][0] > input[largest_key][0]:
            largest_key = key
    
    print(largest_key)
    

    要获得最小值,您将使用完全相同的过程,但将运算符切换为小于。

    【讨论】:

    • 这将在 Python 3.6 中引发错误,因为 input.keys() 返回一个对象而不是一个列表。你应该把它改成keys = list(input.keys())
    【解决方案3】:

    您可以对 dict 的值进行排序并访问最大和最小的值,如下所示:

    my_dict={5: [379], 11: [396], 6: [480], 19: [443]}
    
    
    sorted_list = sorted([value for key,value in my_dict.items()])
    
    max_val = sorted_list[-1][0]
    min_val = sorted_list[0][0]
    
    max_key = list(my_dict.keys())[list(my_dict.values()).index([max_val])]
    min_key = list(my_dict.keys())[list(my_dict.values()).index([min_val])]
    
    print(min_key, max_key)
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多