Programming

[] 및 {} vs list () 및 dict (), 어느 것이 더 낫습니까?

procodes 2020. 8. 24. 21:17
반응형

[] 및 {} vs list () 및 dict (), 어느 것이 더 낫습니까?


나는 그것들이 본질적으로 동일하다는 것을 이해하지만 스타일 측면에서 빈 목록이나 사전을 만드는 데 사용하는 것이 더 나은 (더 Pythonic) 하나입니까?


속도면에서 빈 목록 / 딕셔너리에 대한 경쟁이 아닙니다.

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

또한 대괄호 표기법을 사용하면 목록 및 사전 이해도를 사용할 수 있으므로 충분한 이유가 될 수 있습니다.


내 의견 []{}빈 목록 / dicts을 생성 할 수있는 가장 파이썬 읽을 수있는 방법이 있습니다.

주의하십시오 set(), 예를 들어,하지만이야 '

this_set = {5}
some_other_set = {}

혼란 스러울 수 있습니다. 첫 번째는 하나의 요소로 집합을 만들고 두 번째 는 집합이 아닌 빈 사전을 만듭니다 .


DICT의 문자가있을 수 있습니다 작은 그 바이트 코드가 짧은로 빠른 비트 :

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에도 동일하게 적용됩니다.[]


IMHO, 사용 list()하고 dict()Python을 C. Ugh처럼 보이게 만듭니다.


[]와 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'] 

아래 예제와 같이 []와 list () 사이의 동작에는 한 가지 차이점이 있습니다. 숫자 목록을 반환하려면 list ()를 사용해야합니다. 그렇지 않으면지도 객체를 얻습니다! 그래도 설명하는 방법을 모르겠습니다.

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

timeit doesn't seem to give accurate time. As per the timeit benchmark mentioned above for dict(), it seems to take ~200ms which is way slower than normal http calls. Try running in shell , dict() and then timeit("dict()"), you would see visible difference in execution; timeit("dict()") takes longer. Copy paste following piece of code and run in shell, you would not see much difference in both {} & dict().

    from datetime import datetime
    then = datetime.now()
    a = dict()
    now = datetime.now()
    print then
    print now

    then = datetime.now()
    b = {}
    now = datetime.now()
    print then
    print now

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

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

반응형