방금 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})
>>>
나는 당신이 뭘 하려는지 이해가 안 돼요. 'thing'과'foo'는 무엇이고'thing'은 0을 반환해야하는 이유는 무엇입니까? – jadkik94
명확히하기 위해 :'(range (3)에있는 i에 대한) thing ((i, i * i))'는'defaultdict' 인스턴스를 반환해야합니다. 나는 그 질문을 명확하게하기 위해 편집 할 것이다. – wim
오, 좋아,'-1'은 그것이 그것이 누락 된 색인 이라기보다 목록이라고 생각하게했다. 만약 당신이 이것을하는'default_factory'를 원한다면, 나는 그것을 할 수 있다고 생각하지 않는다. 왜냐하면 (문서들로부터) "기본 팩토리는 *** 인자없이 호출되어 *** 키가 생성 될 때 새로운 값을 생성하기 때문이다. __getitem__에만 존재합니다. " – jadkik94