【问题标题】:TypeError: list indices must be integers or slices, not float;TypeError:列表索引必须是整数或切片,而不是浮点数;
【发布时间】:2020-01-15 18:14:34
【问题描述】:

我遇到了错误:

TypeError: list indices must be integers or slices, not float

在我下面这行代码中:

a1[j+1] = key

下面是我的代码:

a1 = [4.3, 5.2, 5.0, 1.5, 3.8, 4.1, 5.5, 1.9]
sum = 0
count = len(a1)
for i in a1:
    sum = sum + float(i)
    key = a1[index]
    j = i-1
    while j >= 0 and key < j : 
        a1[j + 1] = a1[j] 
        j -= 1
    a1[j+1] = key 
mean = sum/count
print("Answer for y = 1.5")
print("Average: {0}".format(mean))

我想要一个插入排序来对数组 a1 进行排序

【问题讨论】:

  • i 是列表元素,而不是它的索引。所以j = i-1 没有给你插入的地方。
  • index 中的a1[index] 是什么?
  • 您使用while 循环而不是a1.insert() 是否有原因?
  • 如果您想了解如何进行插入排序,请搜索“[python] 插入排序”

标签: python insertion-sort


【解决方案1】:

对于插入排序,您可以试试这个。但是,使用您的方法找出总数将导致错误的 ans,因为 a1 在每次迭代中都会被修改,并且会导致总数的计算不正确。相反,您可以使用 python 提供的 sum() 方法来计算列表的总数。

a1 = [4.3, 5.2, 5.0, 1.5, 3.8, 4.1, 5.5, 1.9]
total = 0
count = len(a1)
for i in range(1, len(a1)):
    key = a1[i] 
    j = i-1
    while j >=0 and key < a1[j] : 
        a1[j+1] = a1[j] 
        j -= 1
    a1[j+1] = key

total =sum(a1)
mean = total/count
print("Answer for y = 1.5")
print("Average: {0}".format(mean))
print(a1)

输出:

Answer for y = 1.5
Average: 3.9124999999999996
[1.5, 1.9, 3.8, 4.1, 4.3, 5.0, 5.2, 5.5]

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 2016-06-23
    • 2021-07-19
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2019-07-04
    • 2015-12-09
    相关资源
    最近更新 更多