2017-08-03 126 views
-2

我已经找到了解决这个问题的方法,也许我找不到任何东西,或者我甚至不能识别正确的解决方案。python的indexerror初学者

我已经完成了这个任务为一疗程,代码工作,但是当我把它变成一个代码测试仪(用于类),我得到以下信息:

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

我该如何摆脱此错误? 顺便说一句,这是一个尝试创建游戏“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]) 
+0

作为一个方面说明,你可以删除你'else:pass'语句。它们是多余的,不需要。没有它们,你的代码会更容易阅读。 – 16num

+1

请修正您的代码的缩进。 – Matthias

回答

0

如果问题是这行代码:

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

我想这是一个由于您使用的测试仪而导致的问题。更具体地说,它甚至在错误的输入上测试你的代码,就像一个空数组。所以,你可以尝试插入输入一些控件,比如下一个:

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

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

0

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

下面是一个示例,其中merge()被调用三次,第二次被调用时没有足够的数字来使函数正常工作,这会触发一个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]))