python - 是否可以在 python 中为 dict 行设置别名?
问题描述
我认为答案是否定的,但想问后代:-)
今天我在我的代码库中发现了有趣的错误。
这是一些上下文:
>>> d1={1:[1], 2:[2], 3:[3]} ### in practice I have more complex data but [] is correct
>>> a1=d1[2] ### I wanted to use a1 as alias, in 15x places
>>> id(d1)
4503224000
>>> id(a1)
4504750528
>>> id(d1[2])
4504750528
>>> d1
{1: [1], 2: [2], 3: [3]}
>>> a1
[2]
>>> a1[0] = 22 ### this also correct, I know it is hack
>>> d1 ### value is original dict is changed
{1: [1], 2: [22], 3: [3]}
>>> a1
[22]
>>> del a1 ### now I want to delete it
>>> a1 ### it is deleted
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a1' is not defined
>>> d1 ### but not in original dict
{1: [1], 2: [22], 3: [3]}
>>> del d1[2] ### must be deleted directly
>>> d1
{1: [1], 3: [3]}
我了解正在发生的事情以及原因。
但我很好奇有没有办法将 a1 作为原始 d1[2] 的别名,所以当 del a1 完成时它与 del d1[2] 相同?
PS 我有这个想法是因为我受到 C/C++ 的不良影响。
解决方案
推荐阅读
- node.js - Sequelize addColumn() 迁移挂了
- javascript - 如何使用javascript重定向上一页
- python - 是否可以将属性注册为 abc.abstractmethod 覆盖?
- flutter - 如何在 Flutter CustomPaint 中处理运动手势?
- flutter - 放大Flutter:如何实现自动登录并获取authToken
- cypress - Cypress 并仅运行 cypress.json 的 testFiles 部分中指定的文件
- python - 使用 send_keys (Keys.CONTROL, "v") 复制的打印元素
- reactjs - 为什么我不能渲染自动完成?
- java - java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
- javascript - 大使 Keyclock 设置 redurect_uri 与大使注销