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

2024-09-30 05:32:39 发布

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

我刚接触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

如何避免这种情况


Tags: 项目代码inputintgradegradessortedenter
3条回答

假设您已经将成绩收集到名为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中进一步讨论:

Like strings (and all other built-in sequence type), lists can be indexed and sliced:

>>> 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]

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:

>>> 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]

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

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使用:符号进行列表切片。所以不要使用topthree = sorted_grades[-1,-2,-3],而是使用topthree = sorted_grades[-1:-4:-1]。 列表切片的格式是[start:stop:step]

相关问题 更多 >

    热门问题