def mergeList(lst1,lst2):
lst3=[]
lst4=[]
if len(lst1)>len(lst2):
for i in range(len(lst2)):
lst3.append(lst1[i])
lst3.append(lst2[i])
lst4=lst1[len(lst2):len(lst1)] #here is python giving an error
for j in lst4:
lst3.append(lst4[j])
else:
for i in range(len(lst1)):
lst3.append(lst1[i])
lst3.append(lst2[i])
lst4=lst2[len(lst1):len(lst2)]
for j in lst4:
lst3.append(lst4[j])
return lst3
此程序通过交叉排列两个列表的项来合并它们,但是如果一个列表大于另一个列表,则较大列表的其余项应逐项添加到合并列表(lst3),而不是作为列表。你知道吗
我得到的索引超出了这一行的范围:lst3.append(lst4[j])。你知道吗
我真的很感激任何有助于改进代码和解决问题的建议。 先谢谢你。你知道吗
Python
list
是零索引的。由于由len()
确定的长度是一个索引,因此list
不包含索引等于其长度的元素。因此,到len(lst1)
的lst1
片将失败。如果要一直到lst1
的结尾,只需省略切片的结尾,使用lst1[len(lst2):]
。你知道吗但是,使用
zip()
可以更轻松地完成任务,这将允许您交错项目,然后将剩余的片段(如果需要)添加到结果中:相关问题 更多 >
编程相关推荐