问题:[]和{}与list()和dict(),哪个更好?
我知道它们本质上是同一件事,但是就样式而言,哪个是创建空列表或字典的更好(更Pythonic的)?
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?
回答 0
在速度方面,空列表/字典没有竞争:
>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
0.1821558326547077
对于非空:
>>> 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
另外,使用方括号表示法还可以使您使用列表和字典理解,这可能就足够了。
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.
回答 1
我认为[]
并且{}
是创建空列表/字典的最Python易懂的方法。
不过请注意set()
,例如:
this_set = {5}
some_other_set = {}
可能会造成混乱。第一个创建一个带有一个元素的集合,第二个创建一个空字典而不是一个集合。
In my opinion []
and {}
are the most pythonic and readable ways to create empty lists/dicts.
Be wary of set()
‘s though, for example:
this_set = {5}
some_other_set = {}
Can be confusing. The first creates a set with one element, the second creates an empty dict and not a set.
回答 2
该字典的文字可能是一个小小的其字节码更短更快一点:
In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()
In [4]: dis.dis(a)
1 0 BUILD_MAP 0
3 RETURN_VALUE
In [5]: dis.dis(b)
1 0 LOAD_GLOBAL 0 (dict)
3 CALL_FUNCTION 0
6 RETURN_VALUE
同样适用于list
VS[]
The dict literal might be a tiny bit faster as its bytecode is shorter:
In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()
In [4]: dis.dis(a)
1 0 BUILD_MAP 0
3 RETURN_VALUE
In [5]: dis.dis(b)
1 0 LOAD_GLOBAL 0 (dict)
3 CALL_FUNCTION 0
6 RETURN_VALUE
Same applies to the list
vs []
回答 3
恕我直言,使用list()
和dict()
让你的Python看起来像C.唉。
IMHO, using list()
and dict()
makes your Python look like C. Ugh.
回答 4
对于[]和list()之间的差异,存在一个陷阱,我没有看到其他人指出过。如果将字典用作列表的成员,则两者将给出完全不同的结果:
In [1]: foo_dict = {"1":"foo", "2":"bar"}
In [2]: [foo_dict]
Out [2]: [{'1': 'foo', '2': 'bar'}]
In [3]: list(foo_dict)
Out [3]: ['1', '2']
In the case of difference between [] and list(), there is a pitfall that I haven’t seen anyone else point out.
If you use a dictionary as a member of the list, the two will give entirely different results:
In [1]: foo_dict = {"1":"foo", "2":"bar"}
In [2]: [foo_dict]
Out [2]: [{'1': 'foo', '2': 'bar'}]
In [3]: list(foo_dict)
Out [3]: ['1', '2']
回答 5
list()和[]的工作方式不同:
>>> def a(p=None):
... print(id(p))
...
>>> for r in range(3):
... a([])
...
139969725291904
139969725291904
139969725291904
>>> for r in range(3):
... a(list())
...
139969725367296
139969725367552
139969725367616
list()总是在堆中创建新对象,但是[]可以出于多种原因重用存储单元。
list() and [] work differently:
>>> def a(p):
... print(id(p))
...
>>> for r in range(3):
... a([])
...
139969725291904
139969725291904
139969725291904
>>> for r in range(3):
... a(list())
...
139969725367296
139969725367552
139969725367616
list() always create new object in heap, but [] can reuse memory cell in many reason.
回答 6
如下所示,[]和list()在行为上有一个区别。如果要返回数字列表,则需要使用list(),否则我们将获得一个map对象!不确定如何解释。
sth = [(1,2), (3,4),(5,6)]
sth2 = map(lambda x: x[1], sth)
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
sth2 = [map(lambda x: x[1], sth)]
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
type(sth2) # list
type(sth2[0]) # map
sth2 = list(map(lambda x: x[1], sth))
print(sth2) #[2, 4, 6]
type(sth2) # list
type(sth2[0]) # int
there is one difference in behavior between [] and list() as example below shows. we need to use list() if we want to have the list of numbers returned, otherwise we get a map object! No sure how to explain it though.
sth = [(1,2), (3,4),(5,6)]
sth2 = map(lambda x: x[1], sth)
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
sth2 = [map(lambda x: x[1], sth)]
print(sth2) # print returns object <map object at 0x000001AB34C1D9B0>
type(sth2) # list
type(sth2[0]) # map
sth2 = list(map(lambda x: x[1], sth))
print(sth2) #[2, 4, 6]
type(sth2) # list
type(sth2[0]) # int
回答 7
方括号对表示列表对象或索引下标my_List [x]中的一个。
大括号对表示字典对象。
a_list = [‘on’,’off’,1,2]
a_dict = {开启:1,关闭:2}
A box bracket pair denotes one of a list object, or an index subscript, my_List[x].
A curly brace pair denotes a dictionary object.
a_list = [‘on’, ‘off’, 1, 2]
a_dict = { on: 1, off: 2 }
回答 8
大多数时候,这主要是选择问题。这是一个偏好问题。
但是请注意,例如,如果您有数字键,则不能这样做:
mydict = dict(1="foo", 2="bar")
你所要做的:
mydict = {"1":"foo", "2":"bar"}
It’s mainly a matter of choice most of the time. It’s a matter of preference.
Note however that if you have numeric keys for example, that you can’t do:
mydict = dict(1="foo", 2="bar")
You have to do:
mydict = {"1":"foo", "2":"bar"}