V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2015-08-28 13:57:33 +08:00 · 3960 次点击
    这是一个创建于 3172 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    4 条回复    2015-09-03 07:53:56 +08:00
    ryd994
        1
    ryd994  
       2015-08-28 14:49:24 +08:00 via Android   ❤️ 1
    既然已知是数字,当然 int 好
    字符串比较性能根本没法比
    WKPlus
        2
    WKPlus  
       2015-08-28 19:37:27 +08:00   ❤️ 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  
       2015-08-29 21:53:52 +08:00 via Android
    @WKPlus nice point ,学习了
    guoqiao
        4
    guoqiao  
       2015-09-03 07:53:56 +08:00
    @WKPlus 我也想当然的觉得 int 更快, 实际却不是. 赞科学严谨的态度.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1641 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 16:23 · PVG 00:23 · LAX 09:23 · JFK 12:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.