字典,python函数,全局变量和局部变量,内存

时间:2018-01-30 17:41:10

标签: python variables dictionary global local

我有一些看起来像这样的代码:

>>> dataDict1 = {'feature1': [], 'feature2': [], 'feature3': []}
>>> features = {0 : 'feature1', 1: 'feature2', 2: 'feature3'}
>>>
>>> def f(data_Dict, featureLabel):
...     data_Dict[featureLabel] = [1, 2]
...     return data_Dict
>>>
>>> for i in range(3):
...     dataDict2 = f(dataDict1, features[i])
...     print dataDict2
...
{'feature2': [], 'feature3': [], 'feature1': [1, 2]}
{'feature2': [1, 2], 'feature3': [], 'feature1': [1, 2]}
{'feature2': [1, 2], 'feature3': [1, 2], 'feature1': [1, 2]}
>>>
>>> dataDict2
{'feature2': [1, 2], 'feature3': [1, 2], 'feature1': [1, 2]}
>>> dataDict3 = f(dataDict2, 'feature4')
>>>
>>> dataDict3
{'feature4': [1, 2], 'feature2': [1, 2], 'feature3': [1, 2], 'feature1': [1, 2]}
>>> dataDict2
>>>
{'feature4': [1, 2], 'feature2': [1, 2], 'feature3': [1, 2], 'feature1': [1, 2]}

我想我明白这里到底发生了什么。但是当我输入dataDict1时,我得到的与dataDict2和dataDict 3完全相同。

>>> dataDict1
{'feature4': [1, 2], 'feature2': [1, 2], 'feature3': [1, 2], 'feature1': [1, 2]}
>>>

我期望dataDict1为

{'feature2': [1, 2], 'feature3': [1, 2], 'feature1': [1, 2]}

我认为我对python return语句的工作方式并不了解。或者可能是局部和全局变量。有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

这一行:

...     data_Dict[featureLabel] = [1, 2]

修改参数data_Dict。如果你不想(似乎)函数修改它的参数,你需要首先克隆参数:

...     data_Dict = dict(data_Dict)
...     data_Dict[featureLabel] = [1, 2]