我不知道这个问题是否微不足道。但是经过几个小时的搜索,我决定在这里问一下。考虑以下代码:
from collections import defaultdict
d = defaultdict(int)
据我所知,d
只接受 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
.
最佳答案
您想查看 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
当你创建一个默认字典时,你实际上只是在指定为未定义的键提供值的工厂函数,仅此而已。
关于python - 如何获取 defaultdict 中值的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9170855/