2017-09-04 118 views
-2

我使用Python 3.4.2Python列表返回指向

def change(list_3,n): 
    list_3[n] = 'x' 
    return list_3 

def simulate(list_2): 
    list_4 = [] 
    for i in range(len(list_2)): 
     list_4.append(change(list_2,i)) 
    return list_4 

list_1 = [' ',' '] 
simulate(list_1) 

当我运行这段代码我希望它返回:[['x',' '],[' ','x']] 而是它返回[['x','x'],['x','x']]它改变LIST_1到['x','x']。看起来这是因为函数更改接收到一个指针,它使其编辑li​​st_1。并且它还返回一个指针,它在list_1被更改时导致list_4自身更新。

有谁知道我可以如何让python转移实际上在列表中而不是给一个指针?

+0

第一误差在模拟函数'i相同,项(变化(列表中,i))的 : '将'list'改为'list_2' – Kallz

回答

0

不要将列表视为指针,将其视为对象。这个对象是可变的。 Python不会将新对象创建为副作用(在您的名称空间中),因此任何新对象都必须位于具有赋值的行上,例如, =return某处。

在你的问题中,你调用list_3[n] = 'x',并返回相同的列表。如果您返回了重复(例如list(list_3)list_3[:]),那么您会看到您的预期。

为了进一步阐述 - 考虑重新编写代码如下(不上不下的功能,并增加了打印):

list_1 = [' ',' '] 
list_4 = [] 
list_1[0] = 'x' 
list_4.append(list_1) 
list_1[1] = 'x' 
list_4.append(list_1) 
print list_4 

从本质上讲,你的价值是从函数返回的事实并不意味着你会得到一个新的副本。此外,由于append不会创建副本,因此使用行list_1[1]更新对list_1的两个引用。

0

这是因为列表是可变的。如果数据类型是可变的,则python会传递地址指针,因为您将x添加到同一列表中,并且list4在所有索引中也包含相同的列表。

无论是在枚举(列表)和list_4.append改变逻辑或使用不可变的数据类型等元组

0
def change(list_3,n): 
    list_3[n] = 'x' 
    return list_3 

def simulate(list_2): 
    list_4 = [] 
    for i in range(len(list_2)): 
     list_4.append(change(list(list_2), i)) # this is where I've made my change. I've added the list keyword so that instead of appending the variable name "list_1", the items in list_1 are appended into list_4 
    return list_4 

list_1 = [' ', ' '] 
print(simulate(list_1))