所以,我正在编写一个代码,用于将列表中特定列表的元素向右移动。
def right(state,index):
r_state=state
new_state = []
for j in range(1,len(r_state[index])):
new_state.append(r_state[index][j-1])
new_state.insert(0, r_state[index][-1])
r_state[index]=new_state
return r_state
#case1
for i in range(2):
print(right([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], i))
#case2
def printer(node):
for i in range(2):
print(right(node, i))
printer([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
案例1给出了我想要的输出(只有一个与索引对应的子列表发生了变化):
[[4, 1, 2, 3], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
[[1, 2, 3, 4], [8, 5, 6, 7], [9, 10, 11, 12], [13, 14, 15, 16]]
但是案例2最终更新了我的列表列表
[[4, 1, 2, 3], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
[[4, 1, 2, 3], [8, 5, 6, 7], [9, 10, 11, 12], [13, 14, 15, 16]]
为什么要更新列表?另外,如何修改case2以获得与case 1相同的输出?
答案 0 :(得分:1)
问题是赋值不能在Python中复制。你必须明确复制。在您自己的代码中,要复制列表,请更改
r_state = state
到
r_state = state[:]
此外,您还会看到使用r_state = list(state)
。 Python 3具有更明确的含义:
r_state = state.copy()
您还可以使用列表推导来创建新列表。这是一种快速而肮脏的方法,使用模运算来移动序列的元素:
>>> def shift_right(lst, shift):
... modulus = len(lst)
... return [lst[(i + shift)%modulus] for i in range(len(lst))]
...
>>> def right(state, index):
... return [shift_right(sub, 1) if i == index else sub for i, sub in enumerate(state)]
...
>>> test = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
>>> shift_right(test[0], 1)
[2, 3, 4, 1]
>>> shift_right(test[0], 2)
[3, 4, 1, 2]
>>> shift_right(test[0], 3)
[4, 1, 2, 3]
>>> shift_right(test[0], 4)
[1, 2, 3, 4]
>>> shift_right(test[0], 5)
[2, 3, 4, 1]
>>> right(test, 0)
[[2, 3, 4, 1], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> right(test, 1)
[[1, 2, 3, 4], [6, 7, 8, 5], [9, 10, 11, 12], [13, 14, 15, 16]]
最后的理解可能有点过于密集,可以这样写成:
>>> def right(state, index):
... result = []
... for i, sub in enumerate(state):
... if i == index:
... result.append(shift_right(sub, 1))
... else:
... result.append(sub)
... return result
...
>>> right(test, 0)
[[2, 3, 4, 1], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> right(test, 1)
[[1, 2, 3, 4], [6, 7, 8, 5], [9, 10, 11, 12], [13, 14, 15, 16]]
>>> right(test, 2)
[[1, 2, 3, 4], [5, 6, 7, 8], [10, 11, 12, 9], [13, 14, 15, 16]]
>>> right(test, 3)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [14, 15, 16, 13]]
>>>