python - 列表范围内索引的列表索引超出范围错误

标签 python python-3.x list function

我正在尝试索引一个列表以提取第一个 (0) 和第二个 (1) 项目以进行进一步计算。我的代码目前如下所示:

def calculate_scores(list):
    sat = list[0]
    gpa = list[1]
    weighted_sat = (sat / 160)
    weighted_gpa = (gpa * 2)

这是我想用来进行计算的函数。在我的 main 中调用此函数的部分如下所示:

testscores = []
semestergrades = []

testscores.append(floatlist[0:4])
semestergrades.append(floatlist[4:])

calculate_scores(testscores)

测试分数列表从中提取的列表有 8 个项目长,所有项目都是 float 的 - 但是,当我尝试运行此代码时,它给我一个“列表索引超出范围”错误,用于我尝试的部分将变量“gpa”设置为等于列表[1]。然而,它似乎能够运行第一部分,将变量“sat”设置为等于 list[0]。知道为什么会发生这种情况吗?

最佳答案

当您应该使用 .extend() 或仅使用切片结果时,您正在使用 .append():

# floatlist = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
testscores = []
testscores.append(floatlist[0:4])
# testscores = [[0.5, 1.5, 2.5, 3.5]]

那么,您目前的做法是,testscores 是一个包含一个元素的列表,该元素为 floatlist[0:4]。当您尝试使用第二个元素(索引 1)时,您会收到 IndexError。

您可以使用 .extend() 而不是 .append() 将给定可迭代中的所有项目添加到列表中。或者,你可以这样做

testscores = floatlist[0:4]

因为列表切片无论如何都会生成原始副本。

关于python - 列表范围内索引的列表索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584211/

相关文章:

python - 按多个键/值对字典列表进行排序,其中值的顺序应该是特定的

python - 使用 Python tensorflow 进行预测和预测

python try except 作为一个函数来评估表达式

list - 生成列表的所有排列,包括不同大小和重复元素

python - 将列表项从字符串转换为 int(Python)

Python字符串基于不在正则表达式中的字符替换

python - SqlALchemy 外键链接两个表时出错

python - 初始化列表成员

python - 'if __name__ == "__main_ _":' 的用途

python - 在 python (pytest) 测试中使用资源文件