Skip to main content
 首页 » 编程设计

python之为什么Python会修改循环外的列表

2024年11月01日12傻小

对于这个列表:

current_trace = [[3,5,1,5,7,9,4]] 

我运行 sliding_tristep() 方法,其中包括 predict() 和 window() 方法:

def predict(lst): 
    print "predicting for", lst 
    print "result", max(lst) + 0.0 
    return max(lst) + 0.0 
 
def window(lst, n=3): 
    for x in range(1, len(lst)+1): # or len(l)+n to continue till the end 
        yield(lst[max(0, x-n):x]) 
 
def sliding_tristep(full_trace, future_step = 2, window_size = 3): 
 
    for user_trace in full_trace: 
        for current_input in window(user_trace): 
            counter = 0 
            trace = current_input 
            accumulator = [] 
            while counter <= future_step: 
                next_prediction = predict(trace)   
                trace.append(next_prediction) 
                accumulator.append(next_prediction) 
                trace = trace[-window_size:] 
                counter += 1 
 
            print current_input, accumulator 

当我运行 sliding_tristep(current_trace) 时,在 print current_input, accumulator 行的输出中,我注意到 current_input 已被修改虽然它不在 sliding_tristep(current_trace) 中进行计算的 while 循环。

我想知道为什么会这样? python怎么可能修改一个在后续循环中根本没有使用的列表。

请您参考如下方法:

I run sliding_tristep(current_trace), in the output for the print current_input, accumulator line I notice that the current_trace has been modified

刚刚测试了你的代码:

>>> current_trace = [[3,5,1,5,7,9,4]] 
>>> sliding_tristep(current_trace) 
... 
>>> current_trace 
[[3, 5, 1, 5, 7, 9, 4]] 

current_trace 不会被修改。

I wonder why does this happen? How is that possible for python to modify a list which is not used at all in the subsequent loop.

不过,我猜你指的是 current_input 而不是 current_trace。

current_input 被修改,因为 trace 是对 current_input 的引用并且 trace 被修改。

如果你想复制一份 current_input 作为 trace,这里有一个方法:

>>> foo = [1,2,3] 
>>> bar = foo[:] 
>>> bar.append(4) 
>>> foo 
[1, 2, 3] 
>>> bar 
[1, 2, 3, 4] 

应用于您的代码:

def sliding_tristep(full_trace, future_step = 2, window_size = 3): 
    for user_trace in full_trace: 
        for current_input in window(user_trace): 
            counter = 0 
            trace = current_input[:] # make a copy of current_input 
            accumulator = [] 
            while counter <= future_step: 
                next_prediction = predict(trace)   
                trace.append(next_prediction) 
                accumulator.append(next_prediction) 
                trace = trace[-window_size:] 
                counter += 1                     
            print current_input, accumulator 

如果您不修改列表的元素(并且由于整数是不可变的,您不能这样做),您可以按照我在上述示例中建议的那样进行浅拷贝。如果您使用的是可变对象(列表 或其他类型的对象),那么您想使用copy 模块进行深度复制。看看这个答案:https://stackoverflow.com/a/184660/1290438关于这个话题。