推荐学习书目
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
2811299
V2EX  ›  Python

python 字典的 key 用 int 好还是 str 好?

  •  
  •   2811299 · Aug 28, 2015 · 4454 views
    This topic created in 3948 days ago, the information mentioned may be changed or developed.

    把从数据库中取出的数据放在一个字典里,

    其中一个 column 编号作为字典的 key,

    请问这个 key 要 int ()一下 还是 str ()一下比较好?

    4 replies    2015-09-03 07:53:56 +08:00
    ryd994
        1
    ryd994  
       Aug 28, 2015 via Android   ❤️ 1
    既然已知是数字,当然 int 好
    字符串比较性能根本没法比
    WKPlus
        2
    WKPlus  
       Aug 28, 2015   ❤️ 3
    数据说话:

    In [18]: d={i:2*i for i in xrange (1000000 )}

    In [19]: %timeit 10000 in d
    10000000 loops, best of 3: 97.9 ns per loop

    In [20]: d={str (i ):2*i for i in xrange (1000000 )}

    In [21]: %timeit "10000" in d
    10000000 loops, best of 3: 92 ns per loop

    看到数据有点吃惊,但转念一想 dict 查找或者插入都先是 hash , hash 之后都是 int 了,比较也是比较的 hash 后的值(除了冲突的时候),所以就再比较一下 str 和 int 计算 hash 的效率:

    In [24]: %timeit hash (12312093810298310928301 )
    10000000 loops, best of 3: 81.7 ns per loop

    In [25]: %timeit hash ("12312093810298310928301")
    10000000 loops, best of 3: 78.5 ns per loop

    如果有冲突,就需要值比对了,理论上来说这时候就需要对 str 进行比较了,应该比较慢了,但是还没有好的方法去寻找两个 hash 值一样的 str ,所以暂时无法测试
    ryd994
        3
    ryd994  
       Aug 29, 2015 via Android
    @WKPlus nice point ,学习了
    guoqiao
        4
    guoqiao  
       Sep 3, 2015
    @WKPlus 我也想当然的觉得 int 更快, 实际却不是. 赞科学严谨的态度.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2647 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 14:38 · PVG 22:38 · LAX 07:38 · JFK 10:38
    ♥ Do have faith in what you're doing.