如何在 Python 的 timeit 中使用 else

Pro*_*o Q 5 python timeit

我是使用 timeit 模块的新手,我很难让多行代码片段在 timeit 内运行。

什么工作:

timeit.timeit(stmt = "if True: print('hi');")
Run Code Online (Sandbox Code Playgroud)

什么不起作用(这些都无法运行):

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')")
Run Code Online (Sandbox Code Playgroud)

我发现我可以使用三引号来封装多行代码段,但我宁愿只在一行上输入。

有没有办法在 timeit 的一行中使用 else 语句?

Uri*_*iel 6

您提供的字符串被解释为源代码,因此您可以使用带三个引号的多行字符串,例如

>>> timeit.timeit(stmt = """if True: 'hi'
... else: 'bye'""")
0.015218939913108187
Run Code Online (Sandbox Code Playgroud)

或者 \n换行(但看起来很乱)

>>> timeit.timeit(stmt = "if True: 'hi'\nelse: 'bye'")
0.015617805548572505
Run Code Online (Sandbox Code Playgroud)

if-else如果您只需要一个分支(因此不需要换行符),您也可以使用三元条件:

>>> timeit.timeit(stmt = "'hi' if True else 'bye'")
0.030958037935647553
Run Code Online (Sandbox Code Playgroud)