[英]How to obtain the type of the values in a defaultdict
I don't know if this question is trivial or not. 我不知道这个问题是否微不足道。 But after a couple of hours searching I decided to ask it here.
但是经过几个小时的搜索后,我决定在这里询问。 Consider the following code:
考虑以下代码:
from collections import defaultdict
d = defaultdict(int)
As far as I know, d
only accepts values of type int
. 据我所知,
d
只接受int
类型的值。 Now if I want to create another variable of the same type as the type of the values in d
, how I do this? 现在,如果我想创建另一个与
d
中的值类型相同的变量,我该怎么做? An impossible code but that may help to understand my question is this one: 不可能的代码,但这可能有助于理解我的问题:
from collections import defaultdict
d = defaultdict(int)
a = 1
if type(a) == d.type_of_values:
print "same type"
else:
print "different type"
It should print "same type", and I'm inventing the existence of the class member type_of_values
, but in this case its value must be int
. 它应该显示“相同类型”,并且我正在发现类成员
type_of_values
的存在,但是在这种情况下,其值必须为int
。
You want to look at default_factory: 您要查看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'>
(To be honest, to find this out, I simply made a defaultdict, typed dir(d) at the console, and looked for something that seemed promising.) (说实话,要找出答案,我只是做了一个defaultdict,在控制台上键入dir(d),然后寻找看起来有希望的东西。)
Incidentally, it's not true that a defaultdict only accepts values of the default type. 顺便说一句,defaultdict只接受默认类型的值并不正确。 For example:
例如:
>>> d = defaultdict(int)
>>> d[10] = 3+4j
>>> d
defaultdict(<type 'int'>, {10: (3+4j)})
>>> d[30]
0
>>> d["fred"]
0
When you make a default dict, you're really only specifying the factory function which gives values for undefined keys, and nothing more. 当您做出默认命令时,您实际上只是在指定工厂函数,该函数提供未定义键的值,仅此而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.