为什么这会超出范围(lst3.append(lst4[j])?

2024-04-26 07:46:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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])。你知道吗

我真的很感激任何有助于改进代码和解决问题的建议。 先谢谢你。你知道吗


Tags: in列表forlenifhereisdef
1条回答
网友
1楼 · 发布于 2024-04-26 07:46:47

Pythonlist是零索引的。由于由len()确定的长度是一个索引,因此list不包含索引等于其长度的元素。因此,到len(lst1)lst1片将失败。如果要一直到lst1的结尾,只需省略切片的结尾,使用lst1[len(lst2):]。你知道吗

但是,使用zip()可以更轻松地完成任务,这将允许您交错项目,然后将剩余的片段(如果需要)添加到结果中:

def mergeList(lst1,lst2):
    lst3 = [item for t in zip(lst1, lst2) for item in t]
    if len(lst2) > len(lst1):
        lst3 += lst2[len(lst1):]
    if len(lst1) > len(lst2):
        lst3 += lst1[len(lst2):]
    return lst3

相关问题 更多 >