2

我不知道这个问题是否微不足道。但经过几个小时的搜索,我决定在这里问它。考虑以下代码:

from collections import defaultdict

d = defaultdict(int)

据我所知,d只接受 type 的值int。现在,如果我想创建另一个与 中的值类型相同类型的变量,d我该怎么做?一个不可能的代码,但可能有助于理解我的问题是这个:

from collections import defaultdict

d = defaultdict(int)    

a = 1
if type(a) == d.type_of_values:
   print "same type"
else:
   print "different type"

它应该打印“相同类型”,并且我正在发明类成员的存在type_of_values,但在这种情况下,它的值必须是int.

4

1 回答 1

4

你想看看 default_factory:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d
defaultdict(<type 'int'>, {})
>>> d.default_factory
<type 'int'>
>>> d = defaultdict(list)
>>> d.default_factory 
<type 'list'>

(老实说,为了弄清楚这一点,我只是做了一个 defaultdict,在控制台输入 dir(d),然后寻找看起来很有希望的东西。)

顺便说一句,defaultdict 只接受默认类型的值是不正确的。例如:

>>> d = defaultdict(int)
>>> d[10] = 3+4j
>>> d
defaultdict(<type 'int'>, {10: (3+4j)})
>>> d[30]
0
>>> d["fred"]
0

当您创建默认字典时,您实际上只是指定了为未定义键提供值的工厂函数,仅此而已。

于 2012-02-07T04:09:50.097 回答