我刚接触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]
但是,在运行topthree时,我收到一个错误:
TypeError: list indices must be integers or slices, not tuple
如何避免这种情况
假设您已经将成绩收集到名为
grades
的列表中:负索引和切片等语法将在tutorial provided in the CPython documentation中进一步讨论:
列表索引/切片的一般格式是
some_list[start:stop:step]
:请注意,列表片是末端独占的,因此
numbers[1:2]
只返回第二个条目:[3]
您需要像这样使用列表切片:
我知道上面写着
-4
,但它需要前三名如果要使用列表,则需要付出更多的努力:
您也可以反向排序:
Python使用
:
符号进行列表切片。所以不要使用topthree = sorted_grades[-1,-2,-3]
,而是使用topthree = sorted_grades[-1:-4:-1]
。 列表切片的格式是[start:stop:step]
相关问题 更多 >
编程相关推荐