打印列表输入的最小值和最大值函数

1 投票
2 回答
3270 浏览
提问于 2025-05-01 10:35

每次我运行代码时,都会出现“类型错误:'int'对象不可迭代”的提示。

所以我的问题是:我该如何在最后打印或使用最小值和最大值的函数?比如说,如果有人输入了5、7、10和-1,我该如何让用户知道最高分是10,最低分是5?(然后我想把这些数字从高到低排列。)

def fillList():

    myList = []

    return myList

studentNumber = 0

myList = []

testScore = int(input ("Please enter a test score "))

while testScore > -1:

      # myList = fillList()

      myList.append (testScore)

      studentNumber += 1

      testScore = int(input ("Please enter a test score "))

print ("")   
print ("{:s}     {:<5d}".format("Number of students", studentNumber))
print ("")
print ("{:s}           ".format("Highest Score"))
print ("")
high = max(testScore)
print ("Lowest score")
print ("")
print ("Average score")
print ("")
print ("Scores, from highest to lowest")
print ("")
暂无标签

2 个回答

0

如果你所有的分数都放在一个数组里。

print("The max was: ",max(array))
print("The min was: ",min(array))
1

你的问题在于 testScore 是一个整数。那它还能是什么呢?每次遍历列表时,你都把它重新赋值为下一个整数。

如果你想把它们添加到一个列表中,你得真的去做这件事:

testScores = []
while testScore > -1:
    testScores.append(testScore)
    # rest of your code

现在这就简单多了:

high = max(testScores)

实际上,在你修改后的代码中,你确实在做这件事:myList 里包含了所有的 testScore 值。所以,直接使用它就行了:

high = max(myList)

不过,仔细想想,其实在你处理的过程中保持一个“当前最大值”也是很简单的:

high = testScore
while testScore > -1:
    if testScore > high:
        high = testScore
    # rest of your code

如果用户从来没有输入任何测试分数,你会看到不同的结果(第一个会因为请求空列表的最大值而引发 TypeError,而第二个会给你 -1),但一旦你决定了想要的结果,这两种情况都很容易修改。

撰写回答