Python I';我得到的索引错误超出了我的代码范围

Python I';我得到的索引错误超出了我的代码范围,python,indexing,Python,Indexing,代码 对行排序数组进行排序的步骤 a的尺寸为m,b的尺寸为n t=int(input()) for i in range(0,t): n,m,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) j=0 x=0 y=0 c=[] while x!=m and y!=n: if a[x]<b[y]: c.appen

代码

对行排序数组进行排序的步骤 a的尺寸为m,b的尺寸为n

t=int(input())
for i in range(0,t):
    n,m,k=map(int,input().split())
    a=list(map(int,input().split()))
    b=list(map(int,input().split()))
j=0
x=0
y=0
c=[]
while x!=m and y!=n:
    if a[x]<b[y]:
        c.append(a[x])
        x+=1
        #j+=1
    elif a[x]==b[y]:
        c.append(a[x])
        x+=1
        y+=1
        #j+=1
    else:
        c.append(b[y])
        y+=1
while x<m:
        c.append(a[x])
        x+=1
while y<n:
        c.append(b[y])
        y+=1
t=int(输入())
对于范围(0,t)内的i:
n、 m,k=map(int,input().split())
a=列表(映射(int,input().split())
b=列表(映射(int,input().split())
j=0
x=0
y=0
c=[]
而x=m和y=n:

如果是[x]欢迎来到StackOverflow!希望这有帮助

c、 追加(b[y])索引器:列表索引超出范围

在python中,列表中的所有项都可以使用它们的索引。在列表中的位置

在代码
c.append(b[y])
中,有两个部分

  • b[y]
    意味着,=>从列表
    b
    获取索引
    y
    处的项目
  • 现在假设您有一个列表
    [0,1,2,3,4]
    。如您所见,此列表只有5个元素。现在,如果我要求python在索引6、7或10处获取一个元素,如何获取?因此,要通知用户您引发了此索引器异常

  • 将获取的项追加到列表c。在此之前,发生了上述错误,所以这部分从未发生过
  • 确保不会发生IndexError的一种方法是使用如下所示的if条件

    if y < len(b):
        c.append(b[y])
    
    如果y

    注意
    列表
    更像一个链表,而不是数组。因此您不需要指定长度

    我没有得到错误,但是想知道如果x[x]==b[y],为什么x和y都会增加(即x+=1,y+=1)。似乎您可以删除此条件并将其上方的条件从[x]b
    数组不是大小
    n
    ,但如果您不向我们显示说明
    b
    大小的代码,我们无法查看它。此外,根据您的识别,不清楚每个循环中都有什么。