我在CodingBat.com上解决了一个Python问题.我写了以下代码,用于打印字符串n次的简单问题 -
def string_times(str, n):
return n * str
Run Code Online (Sandbox Code Playgroud)
官方结果是 -
def string_times(str, n):
result = ""
for i in range(n):
result = result + str
return result
print string_times('hello',3)
Run Code Online (Sandbox Code Playgroud)
两个函数的输出相同.我很好奇字符串乘法(第一个函数)如何在性能基础上对for循环(第二个函数)执行.我的意思是哪一个更快,大多使用?
另外请建议我自己解决这个问题的方法(使用time.clock()或类似的东西)
我们可以使用该timeit模块来测试这个:
python -m timeit "100*'string'"
1000000 loops, best of 3: 0.222 usec per loop
python -m timeit "''.join(['string' for _ in range(100)])"
100000 loops, best of 3: 6.9 usec per loop
python -m timeit "result = ''" "for i in range(100):" " result = result + 'string'"
100000 loops, best of 3: 13.1 usec per loop
Run Code Online (Sandbox Code Playgroud)
您可以看到乘法是更快的选择.您可以注意到虽然字符串连接版本在CPython中并不坏,但在其他Python版本中可能不是这样.你应该总是选择字符串乘法,或者str.join()出于这个原因 - 不仅仅是速度,而是为了可读性和简洁性.
| 归档时间: |
|
| 查看次数: |
843 次 |
| 最近记录: |