我已经学习了PHP,现在我学习了Python。我用这两种语言编写了这段代码,但它的行为有所不同。
PHP:
<?php
$x = [];
$y = $x;
$x['key'] = 'value';
var_dump($x);
var_dump($y);
的Python:
x = {}
y = x
x['key'] = 'value'
print(x)
print(y)
y
在PHP中为空,但在Python中不为。
我想知道为什么......
答案 0 :(得分:4)
在PHP中,当您分配x = {}
y = x.copy()
x['key'] = 'value'
print(x)
print(y)
时,它会复制数组。在Python中,字典是对象,您只需复制引用 - 而不是字典本身。如果你想复制字典,有一种方法:
top
答案 1 :(得分:0)