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

python列表返回指针

python列表返回指针,python,python-3.x,Python,Python 3.x,我正在使用python 3.4.2 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) 当我运行

我正在使用python 3.4.2

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']]
,并将列表1更改为
['x','x']
。这似乎是因为函数更改接收到一个指针,该指针使其编辑列表_1。它还返回一个指针,当列表1发生变化时,该指针会导致列表4自身更新


有人知道如何让python传输列表中的实际内容而不是给出指针吗?

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

在您的问题中,您调用
list_3[n]='x'
,并返回相同的列表。如果您返回了一个副本(例如
list(list_3)
list_3[:]
),那么您将看到您期望的结果

进一步说明-考虑重新编写代码如下(平展函数,并添加打印):


本质上,您的值是从函数返回的这一事实并不意味着您将获得一个新副本。此外,由于
append
不会创建副本,因此对
list_1
的两个引用都会用
list_1[1]
行更新,这是因为list是可变的。如果数据类型是可变的,python将传递地址指针,因为您将x添加到相同的列表中,而list4在所有索引中也包含相同的列表


更改逻辑或使用不可变的数据类型,如tuple

模拟函数中的first error
for i、枚举(列表)和列表4中的项。追加(更改(列表,i)):
change
list
to
list\u 2
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))
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))