【问题标题】:Best solution for a user-inputed list that returns the max value?返回最大值的用户输入列表的最佳解决方案?
【发布时间】:2021-09-12 19:07:17
【问题描述】:

所以我想创建一个用户输入的不同温度的列表,然后打印出最高温度。我使用了以下解决方案,效果很好:

tempList = []

for i in range(0, int(input("How many temps? "))):
    temp = (float(input("Input a temp: ")))
    tempList.append(temp)

print("Temps are: ", tempList, "and the max temp is:", max)

但是,我正在尝试通过循环列表来使用另一种解决方案:

tempList = []

for i in range(0, int(input("How many temps? "))):
    temp = (float(input("Input a temp: ")))
    tempList.append(temp)

print(max(tempList))

max = 0.00

for temp in range(0, len(tempList)):
    if temp > max:
        max = temp
        
print("Temps are: ", tempList, "and the max temp is:", max)

它工作正常,直到打印出“max”结束。当我输入 36.5 或类似的东西时,它给了我 2。我做错了什么?

【问题讨论】:

    标签: python list max


    【解决方案1】:
    1. 不要使用内置函数名作为变量名
    2. 您正在迭代列表的索引
    3. 有一个内置函数 max 可以用于此
    tempList = []
    
    for i in range(0, int(input("How many temps? "))):
        temp = float(input("Input a temp: "))
        tempList.append(temp)
            
    print("Temps are: ", tempList, "and the max temp is:", max(tempList))
    

    【讨论】:

    • 感谢您的意见。你的意思是我正在使用哪个变量名,有一个函数?对不起,愚蠢的问题,我在编程方面真的很新。
    • max 已经是一个内置函数,而您正在设置 max = 0.00 从而覆盖它。
    【解决方案2】:
    temperatures= []
    
    for i in range(0, int(input("Enter Number of Temperatures You Want to Input: "))):
       temp = (float(input("Enter Temperature: "))) 
       temperatures.append(temp)
    
    print(f"Temperatures You Entered {temperatures}\nMaximum Temperature:",max(temperatures))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-27
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 2010-11-05
      相关资源
      最近更新 更多