【问题标题】:Find max values in a dict containing lists在包含列表的字典中查找最大值
【发布时间】:2015-07-04 20:26:15
【问题描述】:

字典得到了years 的密钥,并且每年它都是该年所有 12 个月中所有温度的列表。我的目标是打印出一张表格,从年份开始,然后每个月换行和当月的温度。

主要是用(ATH)标记所有年份的最高温度,并用(YearHighest)标记每年的最高温度。

My current code:
temp_dict= {
    "2010": [2, 3, 4, 5, 7, 3, 20, 29, 34, 2, 10, 1],
    "2011": [2, 7, 4, 5, 9, 3, 20, 9, 34, 2, 10, 10]
}

for key in temp_dict:
    print("Year",key,":")
    x=0
    for temps in temp_dict[key]:
        x=x+1
        print("Month "+str(x)+":%3d"%temps)
    print()

我不确定如何制作 max 函数,我在想这样的事情,但我无法让它工作:

for key in temp_dict:
    ATH = temp_dict[key]
    YearHigh = temp_dict[key][0]
        for temps in temp_dict[key]:
            if temps >= temp_dict[key][0]:
                 YearHigh = temps
    if YearHigh >= ATH:
         ATH = YearHigh

我希望我的输出是什么样的:

Year 2011 :
Month1:  2
Month2:  7
Month3:  4
Month4:  5
Month5:  9
Month6:  3
Month7: 20
Month8:  9
Month9: 34 (YearHighest)(ATH)
Month10:  2
Month11: 10
Month12: 10

Year 2010 :
Month1:  2
Month2:  3
Month3:  4
Month4:  5
Month5:  7
Month6:  3
Month7: 20
Month8: 29
Month9: 34 (YearHighest)(ATH)
Month10:  2
Month11: 10
Month12:  1

【问题讨论】:

    标签: python list python-3.x for-loop dictionary


    【解决方案1】:

    Python 有内置函数max,使用它被认为是一种好习惯。

    一年中的最大值:

    max(temp_dict["2010"])
    

    所有时间最大值:

    max(sum(temp_dict.values(), []))
    

    sum(lists, []) 确实列表展平,相当于

    [] + lists[0] + lists[1]...
    

    【讨论】:

    • 哇,你把秘密sum-list-flatten搬进去了。可能会迷惑人。可以考虑max(month_value for year in temp_dict.values() for month_value in year)。虽然嘿,嵌套生成器也总是让人们感到困惑。
    • 你是对的,这并不明显。我做了一点解释。
    【解决方案2】:

    Python 有一个内置函数 max 可以使用:

    for key in temp_dict:
        print("Year", key,":")
        temps = temp_dict[key]
        max_temp = max(temps)
        max_index = temps.index(max_temp)
        for index, temps in enumerate(temps):
            r = "Month "+str(index+1)+":%3d"%temps
            if index == max_index:
                r += "(YearHighest)(ATH)"
            print(r)
    

    【讨论】:

    • 最高温度相同的两个(或更多)个月呢?
    • @soon 这很简单。您可以删除已经找到的最大值,然后再次使用max,看看是否有两个相同的最大值。
    • 删除之前的最高温度是开销,您可以在循环内将tempsmax_temp 进行比较。
    【解决方案3】:

    你可以试试这样的:

    temp_dict= {
        "2010": [2, 3, 4, 5, 7, 3, 20, 29, 34, 2, 10, 1],
        "2011": [2, 7, 4, 5, 9, 3, 20, 9, 34, 2, 10, 10]
    }
    
    # defines the max of all years with a list comprehension
    global_max_temp = max([ max(year_temps) for year_temps in temp_dict.values() ])
    
    # iterates through each year
    for year, temps in temp_dict.items():
        print("Year {}".format(year))
        for i, temp in enumerate(temps):
            # prepares the output
            temp_string = ["Month{}: {}".format(i+1, temp)]
    
            # builds a list of flags to be displayed
            flags = []
            if temp == max(temps):
                # max in year flag
                flags.append("YearHighest")
            if temp == global_max_temp:
                # absolute max flag
                flags.append("ATH")
    
            # joins temp_string and flags in a single line and prints it
            print(" ".join(temp_string + [ "({})".format(flag) for flag in flags ]))
    

    Python 文档中的有用链接:enumeratelist comprehensionsmax

    【讨论】:

      【解决方案4】:

      这是我的代码。

      temp_dict= {
          "2010": [2, 3, 4, 5, 7, 3, 20, 29, 34, 2, 10, 1],
          "2011": [2, 7, 4, 5, 9, 3, 20, 9, 34, 2, 10, 10]
      }
      
      # Find the highest temp of all years
      ath = max([ max(v) for v in temp_dict.values()])
      
      for key in temp_dict:
          # Output Year
          print("Year{k}:".format(k=key))
          x=0
          # Find max
          max_value = max(temp_dict[key])
          for temps in temp_dict[key]:
              # Output Month 
              x=x+1
              s = "Month {x}:{v:3d}".format(x=str(x), v=temps)
              # Tag the max value
              if max_value == temps:
                  s += "(YearHighest)" 
              if ath == temps:
                  s += "(ATH)"
              print(s)
          print()
      

      这是我的输出。

      Year2010:                                                                                                                                             
      Month 1:  2                                                                                                                                           
      Month 2:  3                                                                                                                                           
      Month 3:  4                                                                                                                                           
      Month 4:  5                                                                                                                                           
      Month 5:  7                                                                                                                                           
      Month 6:  3                                                                                                                                           
      Month 7: 20                                                                                                                                           
      Month 8: 29                                                                                                                                           
      Month 9: 34(YearHighest)(ATH)                                                                                                                         
      Month 10:  2                                                                                                                                          
      Month 11: 10                                                                                                                                          
      Month 12:  1                                                                                                                                          
      
      Year2011:                                                                                                                                             
      Month 1:  2                                                                                                                                           
      Month 2:  7                                                                                                                                           
      Month 3:  4                                                                                                                                           
      Month 4:  5                                                                                                                                           
      Month 5:  9                                                                                                                                           
      Month 6:  3                                                                                                                                           
      Month 7: 20                                                                                                                                           
      Month 8:  9                                                                                                                                           
      Month 9: 34(YearHighest)(ATH)                                                                                                                         
      Month 10:  2                                                                                                                                          
      Month 11: 10                                                                                                                                          
      Month 12: 10
      

      这里需要用到max函数。它可以快速从列表的数字中获取最大值。

      【讨论】:

        猜你喜欢
        • 2016-09-23
        • 2014-10-06
        • 1970-01-01
        • 2018-01-09
        • 1970-01-01
        • 2013-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多