python - 列表索引超出范围,我在 while 循环内的 if 块中遇到错误
问题描述
def merge(a1,a2):
if len(a1)<1:
return a2
if len(a2)<1:
return a1
a1item=a1[0]
a2item=a2[0]
i=1
j=1
merge=[]
while(a1item or a2item):
print(a1item,a2item)
if a1item<a2item:
merge.append(a1item)
a1item=a1[i]
i+=1
else:
merge.append(a2item)
a2item=a2[j]
j+=1
print(merge)
merge([1,2,3],[3,54,100])
当循环指向最后一个元素时,我在a1item=a1[i]如何停止时遇到错误。建议我不使用内置功能
解决方案
你需要自己检查你的界限 - 除此之外,如果你合并[0,1,2,3]
和你肯定会发生另一个错误[0,4,8]
:
而(0或0):
是假的,你的函数不会进入 while 循环。
带有评论的修复:
def merge(a1,a2):
if len(a1)<1:
return a2
if len(a2)<1:
return a1
i=0
j=0
# store result once - micro-optimization
la1 = len(a1)
la2 = len(a2)
m=[] # do not call variables the same as the function, in case you want to recurse
# I removed the variables to hold the current values in favor
# of directly indexing them
while True: # beware of (0 or 0) which is falsy
print(a1[i],a2[j],end=" -> ")
if a1[i] <= a2[j]: # one more "true" value in first if branch
m.append(a1[i]) # if both are same, we take from the 1st list
i+=1 # no need to branch into the else part
else:
m.append(a2[j])
j+=1
print(m)
# stop conditions: if one list is done, add the other to the end of m
if i == la1:
m.extend(a2[j:])
break
if j == la2:
m.extend(a1[i:])
break
return m
print("----",merge([1,6,9],[0,7,8,11]))
输出:
1 0 -> [0]
1 7 -> [0, 1]
6 7 -> [0, 1, 6]
9 7 -> [0, 1, 6, 7]
9 8 -> [0, 1, 6, 7, 8]
9 11 -> [0, 1, 6, 7, 8, 9]
---- [0, 1, 6, 7, 8, 9, 11]
您可以在此处阅读有关列表切片的更多信息:了解切片表示法
推荐阅读
- ios - iOS PDFkit 无法将自定义属性添加到 pdf 文档
- vue.js - 如何阻止更漂亮地在 VS Code 中切换 vue 插值
- sql - Heroku PostgreSQL 按字母顺序按点在前
- javascript - Bootstrap 滑动盒
- xslt - 如何使用 XSL 从父节点复制所有子节点
- android - 如何在xamarin android中禁用左滑动并启用右滑动
- ios - 如何使用自动布局在对象之间创建间隙
- python - 仅颜色条,具有自定义颜色、值和渐变
- php - PHP & MySQL 登录脚本没有反应
- c# - 如何在 Unity3d 的 (.) 语句中使用变量