当我尝试将namedtuple转换为字典[python 2.7.12]时,使用以下方法,发现addr
比第一种方法慢10倍以上。任何人都可以告诉我这背后的原因是什么?
namedtuple._as_dict()
答案 0 :(得分:3)
因为._asdict
返回OrderedDictionary
:
>>> c._asdict()
OrderedDict([('name', 'john'), ('date', '10-2-2017'), ('foo', 20.78), ('bar', 'python')])
>>>
注意,如果您不关心订单,那么使用字典文字应该是最快的方式:
In [5]: %timeit dict(name=c.name,date=c.date,foo=c.foo,bar=c.bar)
...:
The slowest run took 6.13 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 795 ns per loop
In [6]: %timeit c._asdict()
The slowest run took 4.13 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 2.25 µs per loop
In [7]: %timeit {'name':c.name, 'date':c.date, 'foo':c.foo, 'bar':c.bar}
The slowest run took 7.08 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 424 ns per loop