我明白这个错误意味着什么,但有人可以解释我对这个特定代码的错误吗?基本上,路径= [A,B,C,D],我只是创建[4] [4](最终)二维数组,交换相邻的索引。交换从最后一个元素和之前的元素开始,并在循环开始时转到列表的开头。所以最后我得到[[A,B,D,C] [A,C,B,D],[B,A,C,D],[D,B,C,A]]
t = -1
s = 1
y = []
final = []
path = self.path #path = [A,B,C,D]
for x in path:
y.append(path)
if s < 4: #Just ensuring to not get out of range
y[-s],y[-s-1] = y[-s-1],y[-s]
else:
y[-1],y[0] = y[0],y[-1]
final.append(y)
y = [] # So I won't create multi-dimensional list
错误:列表索引超出范围
答案 0 :(得分:0)
因为此处y
变为[[A, B, C, D]]
而不是[A, B, C, D]
。所以它只有一个元素。
答案 1 :(得分:0)
这是一段有效且可读的代码:
path= ['A','B','C','D']
final= []
for index in range(len(path)):
row= path[:] # copy the original list
row[index-1],row[index]= row[index],row[index-1] # swap 2 elements
final.insert(0, row) # insert at the start so the order is as expected
print(final)