【发布时间】: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