コードの簡単な説明辞書をすべての辞書に上書きする関数
メインコードは最初に私の関数に渡される空白の辞書を作成します。この関数は、各数値の数を計算し、辞書を更新して返します。しかし、関数が実行されると、入力 'blank_dictionary'はそれが返す辞書( 'new_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}
どうもありがとうございました
[辞書をコピーしてのみ編集する方法](http://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy)の可能な複製) –
はい、ありがとう@PierPaolo。 – PurpleDiane
[変数と代入がPythonでどのように動作するかを読む](https://nedbatchelder.com/text/names.html) – user2357112