【问题标题】:Finding the min of a dictionary value in Python在 Python 中查找字典值的最小值
【发布时间】:2020-07-26 08:49:50
【问题描述】:

我需要找到字典第二个元素的min,而不使用python中的min()函数。需要是一个循环。

比如我的dictionary

sol = {"shape1":[250, 300, 280], "shape2":[46, 70, 5], 
       "shape3":[147, 12, 150], "shape4":[107, 10, 108]}

我应该得到的输出是 shape2,因为第一个值低于另一个形状的第一个值。

任何帮助都会得到帮助

谢谢!

【问题讨论】:

    标签: python dictionary min


    【解决方案1】:

    按字典值使用sorted 的一个班轮

    sol= {"shape1":[250, 300, 280], 
        "shape2":[46, 70, 5], 
        "shape3":[147, 12, 150], 
        "shape4":[107, 10, 108]}
    
    [(k) for k, v in sorted(sol.items(), key=lambda item: item[1][0])][0] # 'shape2'
    

    【讨论】:

      【解决方案2】:

      试试这个:

      sol = {"shape1":[250, 300, 280], "shape2":[46, 70, 5], "shape3":[147, 12, 150], "shape4":[107, 10, 108]}
      
      smallest_shape = ""
      smallest_value = 0
      for i, pair in enumerate(sol.items()):
          if i == 0 or pair[1][0] < smallest_value:
              smallest_shape = pair[0]
              smallest_value = pair[1][0]
      
      print(smallest_shape)
      

      【讨论】:

        猜你喜欢
        • 2015-07-18
        • 2019-02-09
        • 2015-01-16
        • 2013-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-07
        • 1970-01-01
        相关资源
        最近更新 更多