面向初学者的python索引器

面向初学者的python索引器,python,index-error,Python,Index Error,我自己也在寻找解决方案,也许我什么也没找到,也许我甚至无法识别正确的解决方案 我已经完成了一门课程的作业,代码可以正常工作,但当我将其放入代码测试仪(课程要求)时,我收到以下消息: 合并([4])应为[4],但在合并中的第16行收到(异常:IndexError)“列表索引超出范围” 我怎样才能消除这个错误? 顺便说一句,这是创建游戏“2048”的一次尝试,其中非零数字必须向左移动,相同的数字组合将产生双倍的值 2 0 2 4应该变成4 4 0 0 这是我的密码: def merge(li

我自己也在寻找解决方案,也许我什么也没找到,也许我甚至无法识别正确的解决方案

我已经完成了一门课程的作业,代码可以正常工作,但当我将其放入代码测试仪(课程要求)时,我收到以下消息:

合并([4])应为[4],但在合并中的第16行收到(异常:IndexError)“列表索引超出范围”

我怎样才能消除这个错误? 顺便说一句,这是创建游戏“2048”的一次尝试,其中非零数字必须向左移动,相同的数字组合将产生双倍的值

2 0 2 4应该变成4 4 0 0

这是我的密码:

    def merge(line):
        """
        Function that merges a single row or column in 2048.
        """
        new_list = line
        for x in line:
            if x == 0:
                line.remove(0)
                line.append(0)
        if new_list[0] == new_list[1]:
            new_list[0] = new_list[0] * 2
            new_list.pop(1)
            new_list.append(0)
        else:
            pass
        if new_list[1] == new_list[2]:
            new_list[1] = new_list[1] * 2
            new_list.pop(2)
            new_list.append(0)
        else:
            pass
        if new_list[2] == new_list[3]:
            new_list[2] = new_list[2] * 2
            new_list.pop(3)
            new_list.append(0)
        else:
            pass
        return new_list
        return []

    #test
    print '2, 0, 2, 4 becomes', merge([2, 0, 2, 4])

如果问题是这一行代码:

if new_list[1] == new_list[2]:
我想这是由于您使用的测试仪造成的问题。更具体地说,它甚至在错误的输入(如空数组)上测试代码。因此,您可以尝试在输入上插入一些控件,如下所示:

if len(line) === 0: # it checks if the array is empty

此外,对于16num的建议,我建议您删除
return[]
,因为这行代码是不可访问的。

如果代码有效,并且您只希望通过使用try和except来处理错误

下面是一个例子,其中merge()被调用了三次,第二次调用时,函数没有足够的数字工作,这会触发一个索引器,然后传递该索引器,以便代码可以继续运行

def merge(line):
#Function that merges a single row or column in 2048.
    try:
        new_list = line
        for x in line:
            if x == 0:
                line.remove(0)
                line.append(0)
        if new_list[0] == new_list[1]:
            new_list[0] = new_list[0] * 2
            new_list.pop(1)
            new_list.append(0)
        else:
            pass
        if new_list[1] == new_list[2]:
            new_list[1] = new_list[1] * 2
            new_list.pop(2)
            new_list.append(0)
        else:
            pass
        if new_list[2] == new_list[3]:
            new_list[2] = new_list[2] * 2
            new_list.pop(3)
            new_list.append(0)
        else:
            pass
        return new_list
        return []
    except IndexError:
        #print('index error')
        pass


#test
print('2, 0, 2, 4 becomes', merge([2, 0, 2, 4]))
print('2, 0, 2 triggers an index error, which is passed and the code keeps running', merge([2, 0, 2]))
print('2, 0, 2, 4 becomes', merge([2, 0, 2, 4]))

作为旁注,您可以删除
else:pass
语句。它们是多余的,不需要。如果没有它们,您的代码将更容易阅读。请修复代码的缩进。