在Python中查找列表的最小值,最大值

时间:2015-02-27 15:40:32

标签: python

我正在编写一个程序,通过 while循环,获取用户输入的数据并将每个值添加到列表中(它们是温度),直到用户输入“q”(退出) )。我需要找到列表的最小值和最大值。到目前为止,这是我的代码:

temps = []
daily = 1

daily = float(daily)
while daily != "q":
    daily = (raw_input("Today's Temperature: "))
    if str.isdigit(daily) and daily>0:
        temps.append(daily)
    elif daily<0:
        print "Positive temperatures only please."
else: 
    print "Calculating statistics..."

temps = sorted(temps)
print map(float, temps)

maximum = (max(temps))
print "Maximum:",maximum

当我运行它并输入值(90,80,70,60,50,q)时,它工作正常,最小值为90,最小值为50。

然而,当我运行它并输入值(30,28,1,9,26,14,q)时,它返回9作为最大值,1返回最小值。

基本上,它将9.0视为大于8或更小的任何数字。 (即88,56,30等)

我该如何解决?

2 个答案:

答案 0 :(得分:2)

您永远不会将daily转换为循环内的float,因此列表中的所有值都是字符串。作为字符串,"9"大于"30"。同样,您的比较daily>0无法正常工作,因为您要将字符串与数字进行比较;这种情况永远都是正确的 - 除了在Python 3中,它将合理地引发异常。

我建议你尝试这样的事情:

while True:
    daily = raw_input("Today's Temperature: ")
    if daily == "q":
        break
    elif daily.isdigit() and float(daily) > 0:
        temps.append(float(daily))
    else:
        print "Positive numeric temperatures only please."

答案 1 :(得分:1)

我在您的代码中进行了一些更改,因此您可以比较浮点数而不是字符串。我也使用排序而不是映射(但它只是为了向您展示另一种方式)。

temps = []

while True:
    daily = raw_input("Today's Temperature: ")
    if daily == 'q':
        break
    elif daily.isdigit():
        daily = float(daily)  # after this you can do whatever you want with daily as a number
        if daily > 0:
            temps.append(daily)
        elif daily == 0:
            print "Temperature 0 is not allowed."
    else:
        print "Only possitive numbers for temperature please."


temps.sort()
print temps[0]  # returning the minimum value
print temps[-1]  # returning the maximum value

您也可以使用堆(如果您想确保对数运行时间):

import heapq

heapq.heapify(temps)
print heapq.nsmallest(1, temps)
print heapq.nlargest(1, temps)