推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
superbai
V2EX  ›  Python

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

  •  
  •   superbai · Oct 31, 2017 · 2282 views
    This topic created in 3131 days ago, the information mentioned may be changed or developed.
    我以前是写 PHP 的,PHP 里面有一个索引数组的功能感觉很好用,比如说在 PHP 里面,可以这么写
    $array['accountId']['name'] = 'v2ex'

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

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

    在网上查了一些,defaultdict 之类的,感觉也没解决问题。请问是我的代码写的有问题,还是说 Python 的就是如此?有没有什么好的解决方法?
    4 replies    2017-11-01 13:56:02 +08:00
    congeec
        1
    congeec  
       Oct 31, 2017
    这在 PHP 里叫多维数组?在其他语言里叫 Dictionary, Map, Associative Array。
    看 defaultdict
    https://docs.python.org/3/library/collections.html#collections.defaultdict
    CSM
        2
    CSM  
       Oct 31, 2017   ❤️ 1
    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
        3
    Va1n3R  
       Oct 31, 2017
    这还繁琐吗...你没用过 C/C++吧,不对,这貌似就是 PHP 的 feature 吧...不觉得很危险吗
    superbai
        4
    superbai  
    OP
       Nov 1, 2017
    @congeec
    @CSM
    感谢两位,我再仔细看看 defaultdict

    @Va1n3R 恩,不过也很方便吧,看用来做什么
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3126 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 14:00 · PVG 22:00 · LAX 07:00 · JFK 10:00
    ♥ Do have faith in what you're doing.