我刚对类似这样的代码(A)运行了2to3:
def idict(n):
return dict(zip(range(n), range(n)))
它生成了这个(B):
def idict(n):
return dict(list(zip(list(range(n)), list(range(n)))))
既然dict
和zip
都可以处理迭代器,那么为什么需要这个翻译呢?
看起来B也很慢。用以下方法进行测试:
python -m timeit -s "import B as t" "t.idict(10)"
以下是结果:
________________A______B______C___
Python 2.7.13 2.89 3.82 2.29
Python 3.5.1 2.63 4.34 A
例如,默认翻译下,从2.89微秒到4.34微秒(增加50%)。
问题.. (i) 我是否有理由不使用Python 3中的原始代码?(它产生了正确的结果,并且在我看来似乎合理);(ii) 2to3是正确的工具吗?(我们需要在转换约150KLOC的Python时同时运行在2和3上)
更新: 我已将dict(itertools.izip(xrange(n), xrange(n)))
添加为表格中的算法C。
dict.keys()
调用中。推理可能相似,但并不相同。另一个问题也纯粹是关于代码而不是工具的。 - thebjorn