相关疑难解决方法(0)

dict.items()和dict.iteritems()有什么区别?

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)

python dictionary python-2.x

673
推荐指数
6
解决办法
64万
查看次数

time.time vs. timeit.timeit

有时,我喜欢计算运行代码的部分时间.我已经检查了很多在线网站,并且已经看到了两种主要方法.一个是使用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更快,有时速度更慢.哪种方式更好(更准确)?

python performance time python-3.x

30
推荐指数
2
解决办法
1万
查看次数

为什么Python dict理解忽略了dict中的第一个元素?

我想转换成floatsstring值(应该已经被表示为浮动原本)在以下字典:

{'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

0
推荐指数
2
解决办法
182
查看次数