python - 如何从该列表中找到范围、平均值和前三个值而不出现类型错误?

标签 python function sorting range average

我是 python 新手,正在开发一个小项目:

90、75、65、50、40 是以下等级

我的代码:

grade1 = int(input("Enter grade 1:"))
grade2 = int(input("Enter grade 2:"))
grade3 = int(input("Enter grade 3:"))
grade4 = int(input("Enter grade 4:"))
grade5 = int(input("Enter grade 5:"))

numbers = [grade1,grade2,grade3,grade4,grade5]
sorted_grades = sorted(numbers)
topthree = sorted_grades[-1,-2,-3]

但是,在运行 topthird 时我收到错误:

TypeError: list indices must be integers or slices, not tuple

如何避免这种情况?

最佳答案

您需要像这样使用列表切片:

topthree = sorted_grades[:-4:-1]

我知道它说的是-4,但它占据了前三名。

如果你想使用列表,则需要付出更多的努力:

indices = [-1, -2, -3]
topthree = [sorted_grades[i] for i in indices]

您还可以反向排序:

sorted_grades = sorted(numbers, reverse=True)
topthree = sorted_grades[:3]

关于python - 如何从该列表中找到范围、平均值和前三个值而不出现类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975400/

相关文章:

algorithm - big-O notation 和 theta notation 的区别,为什么 (theta) Ө-notation 适合插入排序来描述其最坏情况运行时间?

javascript - 查找点属于哪个六边形的高效算法

python - OpenCV aruco 不能在 Python 中工作(Windows)

MySQL 用户定义的函数在 SELECT 语句中使用时返回不正确的值

javascript - "Maximum call stack size exceeded"从函数内部调用函数

bash - Bash 中的只读别名

python - Tkinter 全局绑定(bind)

python - django 查询集过滤器日期时间字段

python - 无法分配: must be a instance Django foreign Key error

ruby - 对可能包含时间或距离的字符串进行排序