[] 和 {} 与 list() 和 dict(),哪个更好? [英] [] and {} vs list() and dict(), which is better?

查看:25
本文介绍了[] 和 {} 与 list() 和 dict(),哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它们本质上是一回事,但就风格而言,哪个更好(更 Pythonic)用于创建空列表或字典?

解决方案

在速度方面,空列表/字典没有竞争:

<预><代码>>>>从时间导入时间>>>时间([]")0.040084982867934334>>>时间(列表()")0.17704233359267718>>>时间({}")0.033620194745424214>>>时间(字典()")0.1821558326547077

对于非空:

<预><代码>>>>时间([1,2,3]")0.24316302770330367>>>时间(列表((1,2,3))")0.44744206316727286>>>timeit("list(foo)", setup="foo=(1,2,3)")0.446036018543964>>>时间({'a':1,'b':2,'c':3}")0.20868602015059423>>>timeit("dict(a=1, b=2, c=3)")0.47635635255323905>>>timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]")0.9028228448029267

此外,使用括号表示法可以让您使用列表和字典推导式,这可能就足够了.

I understand that they are both essentially the same thing, but in terms of style, which is the better (more Pythonic) one to use to create an empty list or dict?

解决方案

In terms of speed, it's no competition for empty lists/dicts:

>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
0.1821558326547077

and for non-empty:

>>> timeit("[1,2,3]")
0.24316302770330367
>>> timeit("list((1,2,3))")
0.44744206316727286
>>> timeit("list(foo)", setup="foo=(1,2,3)")
0.446036018543964
>>> timeit("{'a':1, 'b':2, 'c':3}")
0.20868602015059423
>>> timeit("dict(a=1, b=2, c=3)")
0.47635635255323905
>>> timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]")
0.9028228448029267

Also, using the bracket notation lets you use list and dictionary comprehensions, which may be reason enough.

这篇关于[] 和 {} 与 list() 和 dict(),哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆