【问题标题】:python which of this two ways of getting set from list is better in terms of efficiency?python 这两种从列表中获取设置的方式中哪一种在效率方面更好?
【发布时间】:2014-09-25 13:37:12
【问题描述】:

python 这两种从列表中获取集合的方式哪一种效率更高?

a)set([1,2,3])

b){s for s in [1,2,3]}

说实话,无论如何,第二种方式对我来说有点奇怪。

falsetru 的提示我试过了:

andi$ python -m timeit '{s for s in [1,2,3]}'
1000000 loops, best of 3: 0.619 usec per loop
andi$ python -m timeit 'set(s for s in [1,2,3])'
1000000 loops, best of 3: 0.911 usec per loop

我使用{} 获得了更好的构造结果。只有在没有任何列表推导的情况下直接传递数组时,set([]) 的构造才能更好地执行。

{} 在 OS X 和某些 EC2 Linux Ubuntu 14.04 LTS 上获得的结果更好

【问题讨论】:

    标签: python list python-2.7 set


    【解决方案1】:

    Timeit他们:

    In [1]: timeit set([1,2,3])
    1000000 loops, best of 3: 359 ns per loop
    
    In [2]: timeit {s for s in [1,2,3]}
    1000000 loops, best of 3: 474 ns per loop
    

    根据上面的结果,给set传递一个列表对象效率更高。

    【讨论】:

    • @falstru 感谢您指出timeit 这是很酷的东西!
    • @andi,真的吗?您使用哪个 Python/平台?以上结果来自 Python 2.7.8 64 位 + Windows 7 位。
    • Python 2.7.6。在 32 位和 64 位模式下,{} 的版本我获得了更好的结果
    • @andi,我在 Python 2.7.6/Ubuntu 14.04 中得到了类似的结果:set(list) 为 270 ns / 集合理解为 429 ns。
    猜你喜欢
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2018-05-24
    • 1970-01-01
    相关资源
    最近更新 更多