[英]Python program to shift elements of array
我正在尝试创建一个 python 程序来洗牌一个数组,以便水平和垂直行永远不会有重复数字。
Input: [1,2,3,4]
Output:
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
我的程序正确计算了每个元素的移位,但是当它将列表附加到输出列表时,输出列表只有列表中最后一项的重复副本。
def numbers(list_of_numbers):
finalValues = [list_of_numbers]
#print(list_of_numbers)
for i in range(1,len(list_of_numbers)):
print("Last array of final: ", finalValues[-1])
tempArray = finalValues[-1]
print("Temp Array: ",tempArray)
temp = tempArray[0]
for j in range(0,len(list_of_numbers)-1):
tempArray[j] = tempArray[j+1]
tempArray[-1] = temp
finalValues.append(tempArray)
print("Final Values: ",finalValues)
return finalValues
numbers([1,2,3,4])
程序输出
[[4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3]]
正确的输出
[[1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]]
问题来自这一行:
tempArray = finalValues[-1]
您不会创建先前列表的副本,而只会创建一个新名称来引用它。 之后,您对tempArray
所有更改实际上都是对此列表的更改,当您最终执行以下操作时:
finalValues.append(tempArray)
您只需在finalValues
添加对同一列表的另一个引用。
最后, finalValues
包含对同一列表的 4 个引用,您可以使用finalValues[0]
、 finalValues[1]
... 访问finalValues[0]
。
您需要的是通过复制前一个列表来创建一个新列表。 一种方法是使用切片:
tempArray = finalValues[-1][:]
您可以在此问题中找到关闭或复制列表的其他方法
因此,完整的代码给出了预期的输出:
Last array of final: [1, 2, 3, 4]
Temp Array: [1, 2, 3, 4]
Final Values: [[1, 2, 3, 4], [2, 3, 4, 1]]
Last array of final: [2, 3, 4, 1]
Temp Array: [2, 3, 4, 1]
Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2]]
Last array of final: [3, 4, 1, 2]
Temp Array: [3, 4, 1, 2]
Final Values: [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
[[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
Thierry 提供了一个非常全面的解释,说明为什么您的代码没有按预期工作。 因此,它是您问题的最佳答案。我添加了我的答案,作为您可以以不太复杂的方式对其进行编码的示例。
创建第一个索引作为数字列表的二维列表。 对于每次迭代,从索引 1 到末尾获取 temp 和切片的最后一个索引,然后添加索引 0。
然后返回列表
def numbers(list_of_numbers):
temp = [list_of_numbers]
for _ in range(1, len(list_of_numbers)):
temp.append(temp[-1][1:] + temp[-1][0:1])
return temp
print(numbers([1,2,3,4]))
输出
[[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]]
问题在于数组的shallow
分配。 您应该进行deep
复制,真正克隆数组,使它们独立。
我是用你自己的代码做的。 您的代码有一些更改:
import copy
它已添加到第一行的import copy
。copy.deepcopy
函数的三种用法,而不是=
(简单赋值)。
import copy
def numbers(list_of_numbers):
finalValues = copy.deepcopy([list_of_numbers])
#print(list_of_numbers)
for i in range(1,len(list_of_numbers)):
print("Last array of final: ", finalValues[-1])
tempArray = copy.deepcopy(finalValues[-1])
print("Temp Array: ",tempArray)
temp = tempArray[0]
for j in range(0,len(list_of_numbers)-1):
tempArray[j] = tempArray[j+1]
tempArray[-1] = temp
finalValues.append(copy.deepcopy(tempArray))
print("Final Values: ",finalValues)
return finalValues
numbers([1,2,3,4])
程序输出
[[4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3], [4, 1, 2, 3]]
程序输出
[[1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.