代码无法使用排序列表和用户输入找到正确的最小值或最大值?

2024-03-28 08:50:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我试图提示用户输入5个整数,然后我要找到最小值、最大值和平均值(后面还有其他内容)。所以我提示并尝试做一个检查,以确保输入是一个整数。然后我试着建立一个列表并对其排序,以找到最小值和最大值。问题是当我在一个数字中有多个数字时,并不总是能找到正确的最小值、最大值和平均值。你知道吗

感谢您的帮助。你知道吗

这是我的密码:

# Define strings minStr = 'Minimum Value is: ' maxStr = 'Maximum Value is: ' aveStr = 'Average Value is: '


# Prompt User for Integers:

strMontyPython = 'My hovercraft is full of eels.  Let\'s sample them.' strMP2 = ' Take 5 samples and enter how many eels you saw on my hovercraft each time below.' print(strMontyPython + strMP2)

# First integer input int1 =input("Please Enter an Eel Count (as an integer).")
# Show knowledge of exceptions initially to check if integer was entered: try:
    val = int(int1) except ValueError:
    print("That's not an integer! \n Fish slap! \n Your min, max, and average will not be computed.")
         print('You\'ve Entered: ' + int1)
#  (Repeat 4 more times)  
# Define functions and useage   
# Make a list to compute min, max values: intList = [int1, int2, int3, int4, int5] 
# Sort list intList.sort()
# Find min print(minStr + intList[0]) 
# Find max print(maxStr + intList[len(intList)-1])  
# Find average value:

def averageEels(int1,int2,int3,int4,int5):
    aveEels = (int1+int2+int3+int4+int5) / (5)

    return aveEels
     print(aveStr + str(averageEels(int(int1),int(int2),int(int3),int(int4),int(int5))))

Tags: andanisvalueintegerminmaxint
1条回答
网友
1楼 · 发布于 2024-03-28 08:50:32

仔细看-你在宣布

intList = [int1, int2, int3, ...]

当你读整数时,它们自然会被读作字符串。你可以把它们打成int,就像你用

val = int(int1)

但是int1仍然是一个字符串,而val仍然是一个int。由于字符串是按字典顺序排序的,10将出现在2之前,依此类推。解决方案是确保在将int1添加到列表之前将其类型转换为整数。你知道吗

下面是对代码的快速清理,使用for循环而不是一遍又一遍地重复代码:

intList = []
for _ in range(0, 5):
    try: 
        val = input("Please Enter an Eel Count (as an integer).")
        intList.append( int(val) )
    except ValueError:
         print("That's not an integer! ...")

此外,python实际上有内置的方法来计算iterable对象的最小值、最大值和平均值(通过“sum/size”),比如列表:

minimum = min(intList)
maximum = max(intList)
average = sum(intList) / len(intList)

如果愿意,您仍然可以通过对列表进行排序来找到这些值,但是没有必要。你知道吗

另一个提示是:如果你想访问列表的最后一个元素,你可以这样做

intList[-1]

python中的负列表索引从列表的后面开始计数:-1是最后一个元素,-2是倒数第二个元素,依此类推。不需要做len(intList) - 1。你知道吗

相关问题 更多 >