我是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:列表索引必须是整数或切片,而不是元组
如何避免这种情况?
答案 0 :(得分:1)
您需要像这样使用列表切片:
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]
答案 1 :(得分:1)
假设您已经将成绩收集到名为grades
的列表中:
# New list of sorted entries
sorted_grades = sorted(grades)
# Sum of all list entries divided by the length
average = sum(grades)/len(grades)
# Last entry minus the first entry
range = grades[-1] - grades[0]
# Slice from the third-to-last entry to the end of the list
top_three = grades[-3:]
tutorial provided in the CPython documentation中进一步讨论了诸如负索引和切片之类的语法:
像字符串(和所有其他内置序列类型)一样,可以对列表进行索引和切片:
>>> squares = [1, 4, 9, 16, 25] >>> squares [1, 4, 9, 16, 25] >>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25]
所有切片操作都返回一个包含所请求元素的新列表。这意味着以下切片将返回列表的新(浅)副本:
>>> squares[:] [1, 4, 9, 16, 25]
列表索引/切片的一般格式为some_list[start:stop:step]
:
>>> numbers = [1,3,5,7,9]
>>> numbers[0:3] # slice from the first element to the third
[1, 3, 5]
>>> numbers[:3] # 0's can be omitted
[1, 3, 5]
>>> numbers[1:3] # slice from the second element to the third
[3, 5]
>>> numbers[3:] # slice from the third element to the end
[7, 9]
>>> numbers[-3:] # slice from the third-to-last to the end
[5, 7, 9]
>>> numbers[::-1] # slice of the whole list, stepping backward by 1 for each entry
[9, 7, 5, 3, 1]
>>> numbers[1::2] # slice of every other entry, starting with the second
[3, 7]
请注意,列表切片是不包含结尾的,因此numbers[1:2]
仅返回第二个条目:[3]
。
答案 2 :(得分:0)
Python使用:
符号进行列表切片。因此,不要使用topthree = sorted_grades[-1,-2,-3]
,而要使用topthree = sorted_grades[-1:-4:-1]
。
列表切片的格式为[start:stop:step]
。