关于 Python 多维数组的问题请教

2017-10-31 17:25:04 +08:00
 superbai
我以前是写 PHP 的,PHP 里面有一个索引数组的功能感觉很好用,比如说在 PHP 里面,可以这么写
$array['accountId']['name'] = 'v2ex'

即使我没有初始化过 accountId 或者 name 这两个 key,PHP 会帮我自动创建

这两天写 Python,发现 Python 中如果使用 dict 来实现相同的功能,需要先判断一下 key 是否存在,然后先进行初始化才能赋值操作,感觉比较繁琐。

在网上查了一些,defaultdict 之类的,感觉也没解决问题。请问是我的代码写的有问题,还是说 Python 的就是如此?有没有什么好的解决方法?
1812 次点击
所在节点    Python
4 条回复
congeec
2017-10-31 17:31:09 +08:00
这在 PHP 里叫多维数组?在其他语言里叫 Dictionary, Map, Associative Array。
看 defaultdict
https://docs.python.org/3/library/collections.html#collections.defaultdict
CSM
2017-10-31 17:38:24 +08:00
from collections import defaultdict
import json

def tree():
"""
Factory that creates a defaultdict that also uses this factory
"""
return defaultdict(tree)

root = tree()
root['Page']['Python']['defaultdict']['Title'] = 'Using defaultdict'
root['Page']['Python']['defaultdict']['Subtitle'] = 'Create a tree'
root['Page']['Java'] = None

print(json.dumps(root, indent=4))

运行结果如下:

{
"Page": {
"Python": {
"defaultdict": {
"Subtitle": "Create a tree",
"Title": "Using defaultdict"
}
},
"Java": null
}
}

https://segmentfault.com/a/1190000010280700
Va1n3R
2017-10-31 17:44:24 +08:00
这还繁琐吗...你没用过 C/C++吧,不对,这貌似就是 PHP 的 feature 吧...不觉得很危险吗
superbai
2017-11-01 13:56:02 +08:00
@congeec
@CSM
感谢两位,我再仔细看看 defaultdict

@Va1n3R 恩,不过也很方便吧,看用来做什么

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/402332

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX