returns 字典覆盖所有字典的函数
Function which returns dictionary overwriting all dictionaries
代码简要说明:
主要代码首先创建一个空白字典,传递给我的函数。该函数计算每个数字的数量并更新随后返回的字典。但是,当函数执行时,它会将输入 'blank_dictionary' 覆盖为与字典相同 returns ('new_dictionary')。为什么会这样?我希望主代码中的 'dictionary' 始终保持空白,以便可以重复使用。
def index_list(lst, blank_dictionary):
new_dictionary = blank_dictionary
for i in lst:
new_dictionary[i] += 1
return new_dictionary
number = 1
maximum = 3
numbers = range(1,maximum+1)
dictionary = {}
for i in numbers:
dictionary[i] = 0
print ('original blank dictionary', dictionary)
new_dictionary = index_list([3,3,3],dictionary)
print ('new dictionary which indexed the list', new_dictionary)
print ('should still be blank, but isnt', dictionary)
输出:
original blank dictionary {1: 0, 2: 0, 3: 0}
new dictionary which indexed the list {1: 0, 2: 0, 3: 3}
should still be blank, but isnt {1: 0, 2: 0, 3: 3}
非常感谢
您正在将 new_dictionary
设置为 参考 为 blank_dictionary
。将行更改为 new_dictionary = dict(blank_dictionary)
就可以了。使用 dict()
构造函数将创建一个新的 new_dictionary
,因此 blank_dictionary
不会被修改。
您可能想调查 collections
模块中的 defaultdict
。如果只需要统计每个元素出现的次数,可以考虑collections.counter
.
此行为不限于听写。在 Python 中,任何时候将可变对象传递给函数时,函数都会对原始对象进行操作,而不是副本。对于像元组和字符串这样的不可变对象,情况并非如此。
但是在这种情况下,没有理由首先将空白字典传递给函数。该函数可以创建一个新字典并 return 它。
代码简要说明:
主要代码首先创建一个空白字典,传递给我的函数。该函数计算每个数字的数量并更新随后返回的字典。但是,当函数执行时,它会将输入 'blank_dictionary' 覆盖为与字典相同 returns ('new_dictionary')。为什么会这样?我希望主代码中的 'dictionary' 始终保持空白,以便可以重复使用。
def index_list(lst, blank_dictionary):
new_dictionary = blank_dictionary
for i in lst:
new_dictionary[i] += 1
return new_dictionary
number = 1
maximum = 3
numbers = range(1,maximum+1)
dictionary = {}
for i in numbers:
dictionary[i] = 0
print ('original blank dictionary', dictionary)
new_dictionary = index_list([3,3,3],dictionary)
print ('new dictionary which indexed the list', new_dictionary)
print ('should still be blank, but isnt', dictionary)
输出:
original blank dictionary {1: 0, 2: 0, 3: 0}
new dictionary which indexed the list {1: 0, 2: 0, 3: 3}
should still be blank, but isnt {1: 0, 2: 0, 3: 3}
非常感谢
您正在将 new_dictionary
设置为 参考 为 blank_dictionary
。将行更改为 new_dictionary = dict(blank_dictionary)
就可以了。使用 dict()
构造函数将创建一个新的 new_dictionary
,因此 blank_dictionary
不会被修改。
您可能想调查 collections
模块中的 defaultdict
。如果只需要统计每个元素出现的次数,可以考虑collections.counter
.
此行为不限于听写。在 Python 中,任何时候将可变对象传递给函数时,函数都会对原始对象进行操作,而不是副本。对于像元组和字符串这样的不可变对象,情况并非如此。
但是在这种情况下,没有理由首先将空白字典传递给函数。该函数可以创建一个新字典并 return 它。