【问题标题】:indexerror in python for a beginner初学者的python中的indexerror
【发布时间】:2018-01-11 01:44:22
【问题描述】:

我自己已经搜索过这个问题的解决方案,也许我什么也没找到,或者我什至无法识别正确的解决方案。

我已经为一门课程完成了这项作业,并且代码可以运行,但是当我将它放入代码测试器(课程所需)时,我收到以下消息:

merge([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])

【问题讨论】:

  • 附带说明,您可以删除 else: pass 语句。它们是多余的,不需要。没有它们,你的代码会更容易阅读。
  • 请修正代码的缩进。

标签: python index-error


【解决方案1】:

如果代码有效,而您只想处理可以使用 try 和 except 完成的错误。

这里有一个例子,merge() 被调用了 3 次,第二次调用时没有足够的数字让函数工作,这会触发一个 IndexError,然后传递它以便代码可以继续运行。

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]))

【讨论】:

    【解决方案2】:

    如果问题出在这行代码:

    if new_list[1] == new_list[2]:
    

    我猜这是您使用的测试仪的问题。更具体地说,即使输入错误,它也会测试您的代码,例如空数组。所以你可以尝试在输入上插入一些控件,比如下一个:

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

    另外,超过16num的建议,我建议你删除return [],因为这行代码是不可达的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 2012-02-26
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多