v = [1, 3, 5, 6, 8, 10]
f = [2, 4, 7, 9, 11, 12]
def new(v,f):
i = 0
j = 0
u=[0]*12
for k in range(12):
if(v[i]<=f[j]):
u[k]+=v[i]
i+=1
elif(f[j]<=v[i]):
u[k]+=f[j]
j+=1
print(u)
new(v, f)
追踪(最近一次呼叫最后一次):
文件“C:/Users/Matheus/PycharmProjects/untitled/dsfdsfs.py”,第15行,
new(v, f)
文件“C:/Users/Matheus/PycharmProjects/untitled/dsfdsfs.py”,第8行,新版
if(v[i]<=f[j]):
IndexError:列表索引超出范围
我无法找出此错误的原因
答案 0 :(得分:1)
当i = 5时,执行if语句的第一个分支,并且i增加到6.在下一个循环中,它尝试将v [6]与f [j]进行比较。这会引发错误。
最好使用while循环,因为您不知道需要的迭代次数。由于python中的列表是可变的,因此使用.append()和.extend()函数将值添加到数组的末尾要容易得多,而不是保留另一个计数器。最后,在while循环结束时,您可以检查哪个列表已用完,导致循环结束,并在结尾添加其他列表。
示例代码:
def new(v,f):
i = 0
j = 0
u = []
# Compare values until one of the lists is exhausted
while i < len(v) and j < len(f):
if(v[i]<=f[j]):
u.append(v[i])
i+=1
elif(f[j]<=v[i]):
u.append(f[j])
j+=1
# Check which list was exhausted and add the rest of the other
# list on the end of the new list
if i >= len(v):
u.extend(f[j:])
else:
u.extend(v[i:])
print(u)
答案 1 :(得分:0)
这种情况正在发生,因为列表v和f的长度都只有6长。 当代码运行时,i增加到5,导致错误。
如果在for循环中添加try / except块,然后打印出来 i,j和k的值你会看到失败:
for k in range(12):
try:
....
except IndexError as err:
print(err)
print("i = ", i)
print("j = ", j)
print("k = ", k)
答案 2 :(得分:0)
看起来您正在尝试将两个列表合并为一个排序列表?
这会快得多:
sorted(v+f)