This question already has answers here:
Why can a function modify some arguments as perceived by the caller, but not others?
(11个答案)
3年前关闭。
所以这个问题很奇怪。我编写了一种算法,可以将任何列表(数组)的内容向左移动给定的位数。
而且,显然,当键入
问题是:如果我将相同的调用放入下面的
所以这段代码
返回此
在控制台中。这是疯狂的,完全错误的。这是为什么?
在第一个循环
如@depperm在评论中所述,一种简单的解决方案是传递列表的副本:
输出:
(11个答案)
3年前关闭。
所以这个问题很奇怪。我编写了一种算法,可以将任何列表(数组)的内容向左移动给定的位数。
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本身,为什么会发生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]
在控制台中。这是疯狂的,完全错误的。这是为什么?
最佳答案
问题在于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]
关于python - 函数只能单独正常工作,但多次调用时不能正常工作。 Python ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41381949/
10-12 12:20