Python中的list(), dict(), [], {}

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

0. 测试环境

Python 3.6.9

1. 引言

在Python中,listdict作为Python的基础数据结构,经常会用到,其定义形式通常有下面两种:

a = []
b = list()

c = {}
d = dict()

二者有什么区别呢?

2. list() vs []dict() vs {}

  • 运行时间

首先比较一下二者的运行时间,timeit模块主要用来测量Python小段代码的执行时间,默认执行100万次。代码如下:

>>> from timeit import timeit
>>> timeit('[]')
0.05389202758669853
>>> timeit('list()')
0.1250211838632822
>>> timeit('{}')
0.06583642773330212
>>> timeit('dict()')
0.1366278938949108
>>> type({})
<class 'dict'>

从时间上来看,明显[]{}的定义形式更快。

  • 数据类型转换
>>> a = (1, 2, 3)
>>> b = [a]
>>> c = list(a)
>>> b
[(1, 2, 3)]
>>> c
[1, 2, 3]
>>> s = 'abc'
>>> x = [s]
>>> y = list(s)
>>> x
['abc']
>>> y
['a', 'b', 'c']

从上面的代码可以看出,list()除了可以定义之外,还可以对将其它数据类型转换为list,而[]则没有数据类型转换的功能。

3. 为什么[]list()更快

dis库是Python自带的一个库,可以用来分析字节码,而字节码是CPython解释器的实现细节。[]list()的字节码对比如下:

>>> import dis
>>> dis.dis(lambda : [])
  1           0 BUILD_LIST               0
              2 RETURN_VALUE
>>> dis.dis(lambda : list())
  1           0 LOAD_GLOBAL              0 (list)
              2 CALL_FUNCTION            0
              4 RETURN_VALUE

从上面的代码可以看出,list()有符号查找和函数调用的开销,因此其速度更慢。

4. 总结

[]{}定义数据类型速度更快,list()dict()除了能定义数据类型之外,还可以对数据进行类型转换。

References

1.https://stackoverflow.com/questions/5790860/and-vs-list-and-dict-which-is-better

2.https://www.quora.com/In-Python-any-difference-between-using-and-list-or-between-and-dict

3.https://docs.python.org/zh-cn/3/library/timeit.html

4.https://docs.python.org/zh-cn/3/library/dis.html

5.https://stackoverflow.com/questions/30216000/why-is-faster-than-list

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值