dict.items()
和之间是否有任何适用的差异dict.iteritems()
?
从Python文档:
dict.items()
:返回字典的(键,值)对列表的副本.
dict.iteritems()
:在字典(键,值)对上返回一个迭代器.
如果我运行下面的代码,每个似乎都返回对同一对象的引用.我缺少哪些微妙的差异?
#!/usr/bin/python
d={1:'one',2:'two',3:'three'}
print 'd.items():'
for k,v in d.items():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
print 'd.iteritems():'
for k,v in d.iteritems():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
Run Code Online (Sandbox Code Playgroud)
输出:
d.items():
they are the same object
they are the same object
they are the same object
d.iteritems():
they are the same …
Run Code Online (Sandbox Code Playgroud) 有时,我喜欢计算运行代码的部分时间.我已经检查了很多在线网站,并且已经看到了两种主要方法.一个是使用time.time
,另一个是使用timeit.timeit
.
所以,我写了一个非常简单的脚本来比较两者:
from timeit import timeit
from time import time
start = time()
for i in range(100): print('ABC')
print(time()-start, timeit("for i in range(100): print('ABC')", number=1))
Run Code Online (Sandbox Code Playgroud)
基本上,它计算在for循环中打印"ABC"100次所需的时间.左边的数字是结果,time.time
右边的数字是timeit.timeit
:
# First run
0.0 0.012654680972022981
# Second run
0.031000137329101562 0.012747430190149865
# Another run
0.0 0.011262325239660349
# Another run
0.016000032424926758 0.012740166697164025
# Another run
0.016000032424926758 0.0440628627381413
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,有时候,time.time更快,有时速度更慢.哪种方式更好(更准确)?
我想转换成floats
的string
值(应该已经被表示为浮动原本)在以下字典:
{'a': '1.3', 'b': '4'}
Run Code Online (Sandbox Code Playgroud)
如果我尝试词典理解:
{k:float(v) for v in d.values()}
Run Code Online (Sandbox Code Playgroud)
我最终得到了dict中的第二项:
In [191]: {k:float(v) for v in d.values()}
Out[191]: {'b': 4.0}
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
python dictionary key-value python-2.7 dictionary-comprehension
python ×3
dictionary ×2
key-value ×1
performance ×1
python-2.7 ×1
python-2.x ×1
python-3.x ×1
time ×1