3

defaultdict에 대한 호출 가능 팩토리를 이해하기 위해 어떻게 얻을 수 있습니까? 나는 아마 불가능하다고 생각하지만, 왜 좋은 이유를 생각할 수 없는가?초기화 시간에 defaultdict 채우기

>>> def foo(*args): 
...  # TODO 
... 
>>> from collections import defaultdict 
>>> thing = foo(defaultdict, int) 
>>> d = thing((i, i*i) for i in range(3)) 
>>> d[2] 
# should return 4 
>>> d[-1] 
# should return 0 
+2

나는 당신이 뭘 하려는지 이해가 안 돼요. 'thing'과'foo'는 무엇이고'thing'은 0을 반환해야하는 이유는 무엇입니까? – jadkik94

+0

명확히하기 위해 :'(range (3)에있는 i에 대한) thing ((i, i * i))'는'defaultdict' 인스턴스를 반환해야합니다. 나는 그 질문을 명확하게하기 위해 편집 할 것이다. – wim

+0

오, 좋아,'-1'은 그것이 그것이 누락 된 색인 이라기보다 목록이라고 생각하게했다. 만약 당신이 이것을하는'default_factory'를 원한다면, 나는 그것을 할 수 있다고 생각하지 않는다. 왜냐하면 (문서들로부터) "기본 팩토리는 *** 인자없이 호출되어 *** 키가 생성 될 때 새로운 값을 생성하기 때문이다. __getitem__에만 존재합니다. " – jadkik94

답변

6

default_factorydefaultdict에 대한 모든 인수가 dict에 불과 인수처럼 취급됩니다

>>> def initdefaultdict(type_, *args, **kwargs): 
...  d = defaultdict(type_) 
...  d.update(*args, **kwargs) 
...  return d 
... 
>>> thing = initdefaultdict(int, ((i, i+10) for i in range(3))) 
>>> thing 
defaultdict(<type 'int'>, {0: 10, 1: 11, 2: 12}) 
>>> thing[3] 
0 

또는

반환 함수를 원래의 요구 사항을 만족하기 이해는 defaultdict으로하고 작업하게하십시오 :

def defaultdict_factory_factory(default_factory): 
    def defaultdict_factory(*args, **kwargs): 
     return defaultdict(default_factory, *args, **kwargs) 
    return defaultdict_factory 

또는 사용 functools.partial :

def defaultdict_factory_factory(default_factory): 
    return partial(defaultdict, default_factory) 
+0

아주 좋다! 이것은 docs (http://docs.python.org/2/library/collections.html#collections.defaultdict)에 언급되어 있지만'help (defaultdict)'(적어도 Python 2.7을 설치할 때) –

+0

놀랍게도 defaultdict의 문서화 문자열에서 누락되었습니다. 얼마나 많은 다른 파이썬 숨겨진 비밀이 거기에 숨어 ​​있는지 궁금합니다 ... – wim

+0

3.4b2의 docstring에서 여전히 이것이 없으면 다른 사람이 버그 보고서를 제출해야합니다. (나는'defaultdict'가 clinic derby라는 인수에 의해 영향을 받고 있다고 가정하고 있습니다. 따라서 가장 최근의 3.3 릴리스를 확인할 수는 없습니다.) – abarnert

5

방금 ​​defaultdict.update을 찾고 계십니까?

>>> from collections import defaultdict 
>>> thing = defaultdict(int) 
>>> thing.update((i, i*i) for i in range(3)) 
>>> thing 
defaultdict(<type 'int'>, {0: 0, 1: 1, 2: 4}) 

함수에 넣을 수 있습니다.

>>> defaultdict(int, [(i, i*i) for i in range(5)]) 
defaultdict(<type 'int'>, {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}) 

는 그냥 통과 :

>>> def defaultdictinitfactory(type_): # this is your "foo" 
...  def createupdate(*args, **kwargs): 
...    d = defaultdict(type_) 
...    d.update(*args, **kwargs) 
...    return d 
...  return createupdate 
... 
>>> f = defaultdictinitfactory(int) # f is your "thing" 
>>> d = f((i, i*i) for i in range(3)) 
>>> d 
defaultdict(<type 'int'>, {0: 0, 1: 1, 2: 4}) 
>>> 
+0

그건 나에게 발생하지 않았다. 'update'가 None을 반환하지 않으면 거의 작동 할 것입니다! – wim

+0

@wim 나는 마지막 업데이트가 당신이 원하는 것을 성취 할 것이라고 생각한다. –

관련 문제