如何使两个目录条目始终引用相同的浮点值

发布于 2024-09-08 20:47:41 字数 358 浏览 3 评论 0原文

考虑一下:

>>> 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬色的秋千 2024-09-15 20:47:41

只有可变对象才有可能,因此您必须用一些可变对象包装不可变值。事实上,任何可变对象都可以,例如内置列表:

>>> n = [0]
>>> d = { 1 : n, 2 : n }
>>> d
{1: [0], 2: [0]}
>>> d[1][0] = 3
>>> d
{1: [3], 2: [3]}

但是创建自己的类或对象有什么困难呢?

>>> n = type( "number", ( object, ), { "val" : 0, "__repr__" : lambda self: str(self.val) } )()
>>> d = { 1 : n, 2 : n }
>>> d
{1: 0, 2: 0}
>>> d[1].val = 9
>>> d
{1: 9, 2: 9}

工作得一样好;)

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:

>>> n = [0]
>>> d = { 1 : n, 2 : n }
>>> d
{1: [0], 2: [0]}
>>> d[1][0] = 3
>>> d
{1: [3], 2: [3]}

but what's hard in creating your own class or object?

>>> n = type( "number", ( object, ), { "val" : 0, "__repr__" : lambda self: str(self.val) } )()
>>> d = { 1 : n, 2 : n }
>>> d
{1: 0, 2: 0}
>>> d[1].val = 9
>>> d
{1: 9, 2: 9}

Works just as fine ;)

溇涏 2024-09-15 20:47:41

在Python中拥有一种指针的更简单的方法是将你的值打包到一个列表中。

>>> foo = {}
>>> foo[1] = [1.0]
>>> foo[2] = foo[1]

>>> foo
{1: [1.0], 2: [1.0]}

>>> foo[1][0]+=100 # note the [0] to write in the list

>>> foo
{1: [101.0], 2: [101.0]}

有效!

The easier way to have a kind of pointer in python is pack you value in a list.

>>> foo = {}
>>> foo[1] = [1.0]
>>> foo[2] = foo[1]

>>> foo
{1: [1.0], 2: [1.0]}

>>> foo[1][0]+=100 # note the [0] to write in the list

>>> foo
{1: [101.0], 2: [101.0]}

Works !

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文