Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在'中声明变量;如果';语句导致问题_Python_Python 3.x - Fatal编程技术网

Python 在'中声明变量;如果';语句导致问题

Python 在'中声明变量;如果';语句导致问题,python,python-3.x,Python,Python 3.x,我正试图在Python3中创建一个rubic多维数据集。我现在正在执行翻转功能 def flip(topSide, frontSide, row, column, direction): if (direction == "right"): if (topSide == 1): if (frontSide == 2): a = cube[1][row - 1][:] cube[1][row-1][:] = cube[2][row

我正试图在Python3中创建一个rubic多维数据集。我现在正在执行
翻转
功能

def flip(topSide, frontSide, row, column, direction):
if (direction == "right"):
    if (topSide == 1):

       if (frontSide == 2):
           a = cube[1][row - 1][:]
           cube[1][row-1][:] = cube[2][row-1][:]
           cube[2][row - 1][:] = cube[3][row - 1][:]
           cube[3][row - 1][:] = cube[4][row - 1][:]
           cube[4][row - 1][:] = a
           print(a)
我将这些面定义为数字。这是:

green=1
红色=2
黄色=3
橙色=4
白色=5
蓝色=6
当我删除
cube[1][row-1][:]=cube[2][row-1][:]
行时,
a
[2,2,2]
。但是如果我不删除那行
a
[3,3,3]
。我在更改变量之前定义了
a
变量,但它仍然会更改。有没有办法将变量
a
定义为它应该是什么


如果您不理解我的问题,请不要犹豫。让我为您演示一下:

将numpy导入为np
cube=np.random.randint(1,7,size=(3,3,3))
"""
立方体是
数组([[1,4,2],
[5, 6, 3],
[3, 1, 1]],
[[2, 2, 1],
[5, 1, 2],
[5, 1, 3]],
[[3, 2, 2],
[4, 2, 2],
[5, 6, 2]]])
"""
行=1
a=cube[1][row-1][:]
打印(a)#输出:数组([2,2,1])
多维数据集[1][第1行][:]=[10,10,10]
打印(a)#输出:数组([10,10,10])
此行为是因为当您运行
a=cube[1][row-1][:]
时,
cube[1][row-1][:]
的引用被分配给变量
a
。引用意味着,你知道,内存中的地址。因此,如果更改了
cube[1][row-1][:]
a
。因为它们在内存中引用相同的地址

您需要分配它的值,而不是地址。解决方案之一是使用:

a=np.copy(多维数据集[1][row-1][:])
打印(a)#输出:数组([2,2,1])
多维数据集[1][第1行][:]=[10,10,10]
打印(a)#仍然输出:数组([2,2,1])

让我为您演示一下:

将numpy导入为np
cube=np.random.randint(1,7,size=(3,3,3))
"""
立方体是
数组([[1,4,2],
[5, 6, 3],
[3, 1, 1]],
[[2, 2, 1],
[5, 1, 2],
[5, 1, 3]],
[[3, 2, 2],
[4, 2, 2],
[5, 6, 2]]])
"""
行=1
a=cube[1][row-1][:]
打印(a)#输出:数组([2,2,1])
多维数据集[1][第1行][:]=[10,10,10]
打印(a)#输出:数组([10,10,10])
此行为是因为当您运行
a=cube[1][row-1][:]
时,
cube[1][row-1][:]
的引用被分配给变量
a
。引用意味着,你知道,内存中的地址。因此,如果更改了
cube[1][row-1][:]
a
。因为它们在内存中引用相同的地址

您需要分配它的值,而不是地址。解决方案之一是使用:

a=np.copy(多维数据集[1][row-1][:])
打印(a)#输出:数组([2,2,1])
多维数据集[1][第1行][:]=[10,10,10]
打印(a)#仍然输出:数组([2,2,1])

多维数据集的类型是什么?它是列表列表还是numpy ndarray?多维数据集的类型是什么?这是一份清单还是一份清单?太谢谢你了,它确实奏效了。但我想知道这是关于NumPy还是Python?不客气。它是关于Python,以及几乎所有其他编程语言的。如果您没有使用C或Java等低级语言的经验,可能会感到困惑。但从这里开始:太谢谢你了,它确实奏效了。但我想知道这是关于NumPy还是Python?不客气。它是关于Python,以及几乎所有其他编程语言的。如果您没有使用C或Java等低级语言的经验,可能会感到困惑。但从这里开始: