我已经找到了解决这个问题的方法,也许我找不到任何东西,或者我甚至不能识别正确的解决方案。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])
作为一个方面说明,你可以删除你'else:pass'语句。它们是多余的,不需要。没有它们,你的代码会更容易阅读。 – 16num
请修正您的代码的缩进。 – Matthias