我正在尝试用Python编写基本的冒泡排序算法,这里是代码:
novac = int(input("Enter number of vaccines : "))
strength = []
midicl = []
if novac in range(0,10):
for x in range(0, novac-1):
strength[x].append(int(input("Enter strength of vaccine {} :".format(x))))
midicl[x].append(int(input(("Enter midichlorian count of patient {} :".format(x)))))
for x in strength:
for y in strength:
if strength[x] < strength[y]:
strength[x], strength[y] = strength[y], strength[x]
print(strength)
else:
print("A maximum of 10 vaccines are allowed")
我收到以下错误,这意味着即使在使用 list.append 方法之后我的列表索引也不在界限内。
Traceback (most recent call last):
File "C:/Users/Aakash/PycharmProjects/Midichlorian/Midichlo.py", line 6, in <module>
strength[x].append(int(input("Enter strength of vaccine {} :".format(x))))
IndexError: list index out of range
答案 0 :(得分:1)
您需要更新以下内容
strength[x].append(int(input("Enter strength of vaccine {} :".format(x))))
midicl[x].append(int(input(("Enter midichlorian count of patient {} :".format(x)))))
到
strength.append(int(input("Enter strength of vaccine {} :".format(x))))
midicl.append(int(input(("Enter midichlorian count of patient {} :".format(x)))))
您无需索引以将元素追加到列表中。