IT

dict.clear ()와 파이썬에서 {} 할당의 차이점

lottoking 2020. 6. 6. 21:10
반응형

dict.clear ()와 파이썬에서 {} 할당의 차이점


파이썬에서 전화를 걸고 사전에 clear()할당하는 것에는 차이가 {}있습니까? 그렇다면 무엇입니까? 예:

d = {"stuff":"things"}
d.clear()   #this way
d = {}      #vs this way


동일한 사전을 참조하는 다른 변수가 있으면 큰 차이가 있습니다.

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

할당 d = {}하면 새로운 빈 사전이 만들어져 d변수에 할당되기 때문 입니다. 이 잎 d2아직도 항목과 이전 사전 가리키는. 그러나 d.clear()동일한 사전 dd2둘 다가 가리키는 사전을 지 웁니다 .


d = {}새 인스턴스를 d만들지 만 다른 모든 참조는 여전히 이전 내용을 가리 킵니다. d.clear()내용을 재설정하지만 동일한 인스턴스에 대한 모든 참조는 여전히 정확합니다.


다른 답변에서 언급 된 차이점 외에도 속도 차이도 있습니다. d = {}가 두 배 빠릅니다.

python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop

python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop

이전에 이미 언급 한 것들에 대한 설명으로 :

>>> a = {1:2}
>>> id(a)
3073677212L
>>> a.clear()
>>> id(a)
3073677212L
>>> a = {}
>>> id(a)
3073675716L

@odano의 답변 외에도 d.clear()여러 번 받아쓰기 를 지우려면 사용 속도가 더 빠릅니다.

import timeit

p1 = ''' 
d = {}
for i in xrange(1000):
    d[i] = i * i
for j in xrange(100):
    d = {}
    for i in xrange(1000):
        d[i] = i * i
'''

p2 = ''' 
d = {}
for i in xrange(1000):
    d[i] = i * i
for j in xrange(100):
    d.clear()
    for i in xrange(1000):
        d[i] = i * i
'''

print timeit.timeit(p1, number=1000)
print timeit.timeit(p2, number=1000)

결과는 다음과 같습니다.

20.0367929935
19.6444659233

원본 객체의 범위가 아닌 경우 변경 방법은 항상 유용합니다.

def fun(d):
    d.clear()
    d["b"] = 2

d={"a": 2}
fun(d)
d          # {'b': 2}

사전을 다시 할당하면 새 객체가 만들어지고 원래 객체는 수정되지 않습니다.


언급되지 않은 한 가지는 범위 지정 문제입니다. 좋은 예는 아니지만 여기에 문제가 발생한 경우가 있습니다.

def conf_decorator(dec):
    """Enables behavior like this:
        @threaded
        def f(): ...

        or

        @threaded(thread=KThread)
        def f(): ...

        (assuming threaded is wrapped with this function.)
        Sends any accumulated kwargs to threaded.
        """
    c_kwargs = {}
    @wraps(dec)
    def wrapped(f=None, **kwargs):
        if f:
            r = dec(f, **c_kwargs)
            c_kwargs = {}
            return r
        else:
            c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment
            return wrapped
    return wrapped

이 솔루션은 대체하는 것입니다 c_kwargs = {}함께c_kwargs.clear()

누군가가 더 실용적인 예를 생각하면 자유롭게이 게시물을 편집하십시오.


In addition, sometimes the dict instance might be a subclass of dict (defaultdict for example). In that case, using clear is preferred, as we don't have to remember the exact type of the dict, and also avoid duplicate code (coupling the clearing line with the initialization line).

x = defaultdict(list)
x[1].append(2)
...
x.clear() # instead of the longer x = defaultdict(list)

참고URL : https://stackoverflow.com/questions/369898/difference-between-dict-clear-and-assigning-in-python

반응형