使用这样的回答,我创建了一个defaultdict的defaultdict秒.现在,我想把那个深层嵌套的dict对象变回普通的python dict.
from collections import defaultdict
factory = lambda: defaultdict(factory)
defdict = factory()
defdict['one']['two']['three']['four'] = 5
# defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'one': defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'two': defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'three': defaultdict(<function <lambda> at 0x10886f0c8>, {
# 'four': 5})})})})
Run Code Online (Sandbox Code Playgroud)
我认为这不是正确的解决方案:
import json
regdict = json.loads(json.dumps(defdict))
# {u'one': {u'two': {u'three': {u'four': 5}}}}
Run Code Online (Sandbox Code Playgroud)
此外,这个答案是不充分的,因为它没有递归嵌套的字典.
我想看到对象.__ new __()的源定义,并决定使用这种快速方式来访问该代码.为什么python给我一个TypeError (is not a type:method),当type()告诉我它是一个类型:方法?
(1)
>>> import inspect
>>> print inspect.getsource(object.__new__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 526, in findsource
file = getfile(object)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 420, in getfile
'function, traceback, frame, or code object'.format(object))
TypeError: <built-in method __new__ of type object at 0x10a2d9410> is …Run Code Online (Sandbox Code Playgroud) 有没有人在python的文件对象实现__enter__和__exit__用例之外有一个真实世界的例子?最好是你自己的,因为我想要实现的是一个更好的方法来概念化它将被使用的情况.
我已经读过了.