Python 是否将dic项目引用作为列表项目?
我的问题是:Python 是否将dic项目引用作为列表项目?,python,Python,我的问题是: >>> row0 = [0, 0, 0] >>> row1 = [0, 0, 0] >>> field = {'hor' : (row0[0], row1[0])} >>> field {'hor': (0, 0)} >>> row0[0] = 1 >>> field {'hor': (0, 0)} 我真正想要的是: >>> field {'hor': (
>>> row0 = [0, 0, 0]
>>> row1 = [0, 0, 0]
>>> field = {'hor' : (row0[0], row1[0])}
>>> field
{'hor': (0, 0)}
>>> row0[0] = 1
>>> field
{'hor': (0, 0)}
我真正想要的是:
>>> field
{'hor': (1, 0)}
我理解这种行为,但我该如何应对呢
我唯一能想到的是:
我可以在字典中存储项目的ID,如下所示:
row0 = [0, 0]
row1 = [0, 0]
field = {'hor' : (id(row0[0]), id(row1[0]))}
但这里的问题是通过id访问变量(我只需要读取访问)。我在谷歌上搜索了一下,发现唯一可能的解决方案是使用globals().items(),如下所示:
for key, value in globals().items(): print key, value, id(value)
我希望有人能更好地解决我的问题。提前谢谢
编辑:
对不起,第一个代码示例有点太简单了。我的案例更像上面的例子。更简单的方法就是:
>>> row = [0, 0, 0] # creating a list object
>>> field = {'row0' : row} # creating a dict with a reference to the list
>>> field # let's see...
{'row0': [0, 0, 0]} # ... looks like this
>>> row[0] = 1 # modifying the list through the name "row"
>>> field
{'row0': [1, 0, 0]} # ... hey, it got modified!
>>> field["row0"][1] = 2 # modifying the list through the dict
>>> row # let's see again...
[1, 2, 0] # ... hey, modified again!
在字典中存储对列表本身的引用,因此
字段[“row0”]
和行
都是对同一列表对象的引用,因此修改其中一个对象将修改另一个对象。更简单的方法是:
>>> row = [0, 0, 0] # creating a list object
>>> field = {'row0' : row} # creating a dict with a reference to the list
>>> field # let's see...
{'row0': [0, 0, 0]} # ... looks like this
>>> row[0] = 1 # modifying the list through the name "row"
>>> field
{'row0': [1, 0, 0]} # ... hey, it got modified!
>>> field["row0"][1] = 2 # modifying the list through the dict
>>> row # let's see again...
[1, 2, 0] # ... hey, modified again!
在字典中存储对列表本身的引用,因此
字段[“row0”]
和行
都是对同一列表对象的引用,因此,修改一个将修改另一个。正如Felix Kling所指出的:你不能像Felix Kling所指出的那样引用原始值:你不能引用原始值,这并不是说你不能通过引用来访问“原始值”。问题是Python中的某些数据类型是可变的(列表、字典),而其他数据类型是不可变的(整数、字符串、元组)。无论何时尝试修改一个不可变对象,都会得到一个具有新值的新对象。原始对象保持不变。所以
a = 3 # create a new object with the value 3 and bind it to the variable 'a'
b = a # bind the variable 'b' to the same object as 'a'
这里“a”和“b”都引用内存中同一位置的同一对象。但是,由于对象是不可变的,因此修改“b”不会产生“预期”结果
b = 4
print a # displays "3"
我们这些来自C/C++的人不习惯“不可变对象”。在C中,您希望“b=4”修改b指向的“对象”,将其值设置为4。在Python中,情况并非如此。“b=4”创建一个值为4的新对象,并修改b,使其指向该新对象。并不是说您不能通过引用访问“原始值”。问题是Python中的某些数据类型是可变的(列表、字典),而其他数据类型是不可变的(整数、字符串、元组)。无论何时尝试修改一个不可变对象,都会得到一个具有新值的新对象。原始对象保持不变。所以
a = 3 # create a new object with the value 3 and bind it to the variable 'a'
b = a # bind the variable 'b' to the same object as 'a'
这里“a”和“b”都引用内存中同一位置的同一对象。但是,由于对象是不可变的,因此修改“b”不会产生“预期”结果
b = 4
print a # displays "3"
我们这些来自C/C++的人不习惯“不可变对象”。在C中,您希望“b=4”修改b指向的“对象”,将其值设置为4。在Python中,情况并非如此。“b=4”创建一个值为4的新对象,并修改b,使其指向此新对象。如果您解释您试图实现的最终结果,可能会有所帮助。关于您的更新:您不能引用原始值。@Felix Kling:如果您将此作为答案发布,我会接受的。如果你解释一下你想要达到什么样的最终结果,可能会有所帮助。关于你的更新:你不能引用原始值。@Felix Kling:如果你把它作为一个答案,我会接受的。