开发者

make a dic item reference a list item?

开发者 https://www.devze.com 2023-03-28 04:46 出处:网络
Here is my problem: >>> row0 = [0, 0, 0] >>> row1 = [0, 0, 0] >>> field = {\'hor\' : (row0[0], row1[0])}

Here is my problem:

>>> 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)}

What I actually want to have would be:

>>> field
{'hor': (1, 0)}

I understand this behaviour, but how can I hack around it?

The only way I could think of was this:

I could store the ID of the items in the dictionary, like this:

r开发者_如何学Cow0 = [0, 0]
row1 = [0, 0]
field = {'hor' : (id(row0[0]), id(row1[0]))}

But the problem here is the access to the variables by the id (I just need read access). I googled a bit, and the only possible solution I found was using globals().items(), like that:

for key, value in globals().items(): print key, value, id(value)

I hope someone has a better solution for my problem. Thanks in advance!

EDIT:

Sorry, the first code example was a bit too simple. My case more looks like the example above.


The simpler way to go about it Just Works:

>>> 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!

Storing a reference to the list itself in the dictionary, so both field["row0"] and row are references to the same list object, hence modifying one will modify the other.


It's not that you can't access "primitive values" by reference. The problem is that some data types in Python are mutable (lists, dictionaries) while others are immutable (integers, strings, tuples). Whenever you try to modify an immutable object, you always get back a new object with the new value. The original object remains untouched. So...

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'

Here both 'a' and 'b' are referencing the same object at the same location in memory. However, because the object is immutable, modifying 'b' does not have the "expected" result...

b = 4  
print a  # displays "3"

Those of us coming from C/C++ aren't used to "immutable objects". In C, you would expect "b = 4" to modify the "object" b is pointing to, setting its value to 4. In Python, this isn't the case. "b = 4" creates a new object whose value is 4 and modifies b so that it points to this new object.


As Felix Kling pointed out: You cannot have a reference to primitive values

0

精彩评论

暂无评论...
验证码 换一张
取 消