如何在 Python 的 timeit 中使用 else
How to use else inside Python's timeit
我是 timeit 模块的新手,我很难在 timeit 中将多行代码片段 运行。
什么有效:
timeit.timeit(stmt = "if True: print('hi');")
什么不行(这些都连不上运行):
timeit.timeit(stmt = "if True: print('hi'); else: print('bye')")
timeit.timeit(stmt = "if True: print('hi') else: print('bye')")
timeit.timeit(stmt = "if True: print('hi');; else: print('bye')")
我发现我可以使用三引号来封装多行代码段,但我宁愿只在一行中键入。
有没有办法在timeit的一行内使用else语句?
您提供的字符串被解释为源代码,因此您可以使用带三个引号的多行字符串,例如
>>> timeit.timeit(stmt = """if True: 'hi'
... else: 'bye'""")
0.015218939913108187
或 \n
换行(但看起来很乱)
>>> timeit.timeit(stmt = "if True: 'hi'\nelse: 'bye'")
0.015617805548572505
如果您只需要一个分支(因此不需要换行符),您也可以使用三元 if-else
条件:
>>> timeit.timeit(stmt = "'hi' if True else 'bye'")
0.030958037935647553
记住条件表达式:<true val> if <condition> else <false val>
当与 timeit 一起使用时,它可能看起来像
timeit.timeit("print('true') if 2+2 == 4 else print('false')")
备注:
- 这个例子将在 python3 中运行,我想将
print
用作函数,因为它最简单。当然你可以 from __future__ import print_function
在 p2.x
- 这个例子显然会输出一个s*itload od "true"s,注意while 运行 it
此代码将按您希望的方式运行:
timeit.timeit("""
if True: print('hi')
else: print('bye')
""")
一定要换行
我的答案是在 this question.
的答案中找到的
您需要在 if
和 else
之间换行,这样才行
timeit.timeit(stmt = "if True: print('hi');\nelse: print('bye')")
我是 timeit 模块的新手,我很难在 timeit 中将多行代码片段 运行。
什么有效:
timeit.timeit(stmt = "if True: print('hi');")
什么不行(这些都连不上运行):
timeit.timeit(stmt = "if True: print('hi'); else: print('bye')")
timeit.timeit(stmt = "if True: print('hi') else: print('bye')")
timeit.timeit(stmt = "if True: print('hi');; else: print('bye')")
我发现我可以使用三引号来封装多行代码段,但我宁愿只在一行中键入。
有没有办法在timeit的一行内使用else语句?
您提供的字符串被解释为源代码,因此您可以使用带三个引号的多行字符串,例如
>>> timeit.timeit(stmt = """if True: 'hi'
... else: 'bye'""")
0.015218939913108187
或 \n
换行(但看起来很乱)
>>> timeit.timeit(stmt = "if True: 'hi'\nelse: 'bye'")
0.015617805548572505
如果您只需要一个分支(因此不需要换行符),您也可以使用三元 if-else
条件:
>>> timeit.timeit(stmt = "'hi' if True else 'bye'")
0.030958037935647553
记住条件表达式:<true val> if <condition> else <false val>
当与 timeit 一起使用时,它可能看起来像
timeit.timeit("print('true') if 2+2 == 4 else print('false')")
备注:
- 这个例子将在 python3 中运行,我想将
print
用作函数,因为它最简单。当然你可以from __future__ import print_function
在 p2.x - 这个例子显然会输出一个s*itload od "true"s,注意while 运行 it
此代码将按您希望的方式运行:
timeit.timeit("""
if True: print('hi')
else: print('bye')
""")
一定要换行
我的答案是在 this question.
的答案中找到的您需要在 if
和 else
之间换行,这样才行
timeit.timeit(stmt = "if True: print('hi');\nelse: print('bye')")