如何使两个目录条目始终引用相同的浮点值
考虑一下:
>>> foo = {}
>>> foo[1] = 1.0
>>> foo[2] = foo[1]
>>> foo
{1: 0.0, 2: 0.0}
>>> foo[1] += 1.0
{1: 1.0, 2: 0.0}
这就是发生的事情。但是,我想要的是最后一行内容为:
{1: 1.0, 2: 1.0}
意味着两者都引用相同的值,即使该值发生变化。我知道上面的代码是这样工作的,因为数字在 Python 中是不可变的。有没有比创建自定义类来存储值更容易的方法?
Consider this:
>>> foo = {}
>>> foo[1] = 1.0
>>> foo[2] = foo[1]
>>> foo
{1: 0.0, 2: 0.0}
>>> foo[1] += 1.0
{1: 1.0, 2: 0.0}
This is what happens. However, what I want would be that the last line reads:
{1: 1.0, 2: 1.0}
Meaning that both refer to the same value, even when that value changes. I know that the above works the way it does because numbers are immutable in Python. Is there any way easier than creating a custom class to store the value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只有可变对象才有可能,因此您必须用一些可变对象包装不可变值。事实上,任何可变对象都可以,例如内置列表:
但是创建自己的类或对象有什么困难呢?
工作得一样好;)
It is possible only with mutable objects, so you have to wrap your immutable value with some mutable object. In fact any mutable object will do, for example built-in list:
but what's hard in creating your own class or object?
Works just as fine ;)
在Python中拥有一种指针的更简单的方法是将你的值打包到一个列表中。
有效!
The easier way to have a kind of pointer in python is pack you value in a list.
Works !