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

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

问题描述

我明白他们本质上是一样的,但是在风格方面,使用哪一个更好(更多的Pythonic)来创建一个空列表或者dict?

解决方案

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

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

和非空: p>

 >>> 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

另外,使用括号表示法可以使用列表和字典解析,这可能是足够的理由。


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 let's you use list and dictionary comprehensions, which may be reason enough.

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

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