我有一些看起来像这样的代码:
>>> 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语句的工作方式并不了解。或者可能是局部和全局变量。有人可以解释一下吗?
答案 0 :(得分:0)
这一行:
... data_Dict[featureLabel] = [1, 2]
修改参数data_Dict
。如果你不想(似乎)函数修改它的参数,你需要首先克隆参数:
... data_Dict = dict(data_Dict)
... data_Dict[featureLabel] = [1, 2]