Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.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 - Fatal编程技术网

函数通常单独工作,但不';打几次电话都不能正常工作。python

函数通常单独工作,但不';打几次电话都不能正常工作。python,python,Python,所以这个问题很奇怪。我编写了一个算法,将任何列表(数组)的内容向左移动给定的位数 DIGS = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] # move functions def move(arr): this = arr first = this[0] for b in range(len(this) - 1): this[b] = this[b + 1] this[-1] = first return this

所以这个问题很奇怪。我编写了一个算法,将任何列表(数组)的内容向左移动给定的位数

DIGS = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

# move functions
def move(arr):
    this = arr
    first = this[0]
    for b in range(len(this) - 1):
        this[b] = this[b + 1]
    this[-1] = first
    return this

def move_with_step(arr, step):
    this_arr = arr
    for a in range(step):
        this_arr = move(arr)
    return this_arr
显然,当键入
print(move_with_step(DIGS,5)
时,我们会得到相同的DIGS数组,但会扭曲。它类似于[5,6,7…3,4]。你明白了。在这种情况下,它是有效的。但是

问题是:如果我像下面这样或一个接一个地将同一个调用放入
for
循环,它会给我错误的结果,这有点奇怪,因为它不应该修改DIGS本身,为什么会发生这种情况

所以这个代码

for a in range(1, 6):
    print(move_with_step(DIGS, a))
还这个

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
[6, 7, 8, 9, 0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]

在控制台中。这是疯狂且完全错误的。为什么会这样?

您应该创建一份DIGS列表的副本以保留原始值。然后,将一份正确的副本传递给函数,它应该可以正常工作


请看一看

问题在于每个循环都会发生变化。因此,当您这样做时:

for a in range(1, 6):
    print(move_with_step(DIGS, a))
在第一个循环的末尾,DIGS=[1,2,3,4,5,6,7,8,9,0]。因此在第二个循环中,它将以已经更改的DIGS开始

如@depperm在评论中所述,一个简单的解决方案是传递列表的副本:

for a in range(1, 6):
    print(move_with_step(DIGS[:], a))
输出:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[2, 3, 4, 5, 6, 7, 8, 9, 0, 1]
[3, 4, 5, 6, 7, 8, 9, 0, 1, 2]
[4, 5, 6, 7, 8, 9, 0, 1, 2, 3]
[5, 6, 7, 8, 9, 0, 1, 2, 3, 4]

DIGS
复制一份,然后将其传递到
move\u(按步骤)
…如
DIGS[:]
或在函数中执行
this\u arr=arr[:]
您是否考虑过使用
集合。如果您觉得有必要,请确认
是否使用
.copy()
,而不是
[:]
会更惯用,让你的意图更清晰。或者只是
list(DIGS)
。这可能更容易理解。@leaf:
DIGS.copy()
更惯用,但应该提到的是,它只在3.3以后才可用(因为OP没有指定使用的Python版本)@不,OP没有说他的Python版本,但我可以假设它是Python3.x,因为这是错误的,它与深拷贝或浅拷贝无关(在这种情况下,两者都可以工作,因为它是一个整数列表)。传递的参数是对列表的引用,没有复制。@我删除了深/浅部分,现在应该是正确的