【问题标题】:Error: list indices must be integers not float错误:列表索引必须是整数而不是浮点数
【发布时间】:2014-01-07 13:23:21
【问题描述】:

下面的代码应该从学生的字典中获取分数列表并计算学生的平均分数。我收到“TypeError:列表索引必须是整数,而不是浮点数”错误。

alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}

# Averege function is given below for calculating avg
def average(lst):
    l=float(len(lst))
    total = 0.0
    #code works till here the error occoured below
    for item in lst:
        add = int(lst[item])
        print add
        total+=add
    return total//l

print average(alice['tests'])
print alice['tests']

【问题讨论】:

  • 你为什么要平均泰勒?
  • @SlaterTyranus 你怎么能平均泰勒? 他是imaginary
  • 抱歉,我给出了一个名为 alice 而不是 tyler 的示例条目

标签: python python-2.7


【解决方案1】:

问题出在这一行:

for item in lst:
    add = int(lst[item])

for item in lst 遍历列表中的每个item,而不是索引。所以item 是列表中浮点数的值。 试试这个:

for item in lst:
    add = int(item)

此外,没有理由强制转换为整数,因为这会影响您的平均值,因此您可以将其进一步缩短为:

for item in lst:
    add = item

这意味着 for 循环可以缩短为:

for item in lst:
    total+= item

这意味着我们可以进一步缩短它,使用内置的sum

total = sum(lst)

由于total现在是一个浮点数,我们不需要用双斜线指定浮点除法,也不再需要将长度转换为浮点数,所以函数变成:

def average(lst):
    l=len(lst)
    total = sum(lst)
    return total/l

最后,没有理由不将所有这些都写在一个易于阅读的行上:

def average(lst):
    return sum(lst)/len(lst)

【讨论】:

  • 非常感谢,它对减少代码长度很有帮助。我肯定会使用这种方法
【解决方案2】:

for item in lst 将让item 在每次迭代中获取lst 中的每一项。所以,改变

add = int(lst[item])

add = int(item)

例如,试试这个以更好地理解

data = ["a", "b", "c"]
for char in data:
    print char

将打印

a
b
c

如果你想获取项目的当前索引,那么你可以使用enumerate函数

data = ["a", "b", "c"]
for index, char in enumerate(data):
    print index, char, data[index]

输出

0 a a
1 b b
2 c c

【讨论】:

  • 非常感谢,它成功了。我在编写代码时正在考虑传统的 for(i=0,,i++) 循环。感谢您让我知道这是错误的方法。
猜你喜欢
  • 2012-11-01
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
  • 2021-07-19
  • 2019-03-03
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多