函数单独正常工作,但在多次调用时不能正常工作。Python

2024-04-26 17:50:44 发布

您现在位置: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

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 ]. 你明白了。在这种情况下,它是有效的。但是。。。你知道吗

The problem is: if I'd put this same call into the for loop like below or just one after another, it will give me wrong results which is kinda strange because it should'n modify DIGS itself and why is that happening IDK.

所以这个代码

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]

在控制台里。这是疯狂和完全错误的。为什么?你知道吗


Tags: informovereturnisdefstepwith
2条回答

问题是在每个循环中挖掘变化。所以当你这么做的时候:

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列表的副本以保留原始值。然后,将一个正确的副本传递给函数,它应该可以正常工作。你知道吗

看看How to clone or copy a list?

相关问题 更多 >