[英]Is there a more efficient way to these for loops in Python 3?
我有以下所有从 1 到 8 的 for 循环。我想知道是否所有这些都可以只包含在 1 个 for 循环中。 它目前不起作用的原因是,如果您从 for 循环中中断,那么它将为所有 if 语句退出它。
for i in range(1, 8):
if Bool1(based on i):
Action1
else:
break
for i in range(1, 8):
if Bool2(based on i):
Action2
else:
break
for i in range(1, 8):
if Bool3(based on i):
Action3
else:
break
for i in range(1, 8):
if Bool4(based on i):
Action4
else:
break
...
你可以这样做:
tests_and_actions = [
(Bool1, Action1),
(Bool2, Action2),
(Bool3, Action3),
(Bool4, Action4),
# ...
]
for test, action in tests_and_actions:
for i in range(1, 8):
if test(based on i):
action()
else:
break
假设以下两个条件:
ActionX
没有副作用,不会导致将来调用BoolY
给出不同的结果。以下(虽然远非漂亮)应该可以工作:
# Flags, indicating which part is still relevant
active1 = True
active2 = True
active3 = True
active4 = True
for i in range(1, 8):
if active1 and Bool1(based on i):
Action1
else:
active1 = False
if active2 and Bool2(based on i):
Action2
else:
active2 = False
...
# The below is just an optimization to avoid superfluous looping.
if not active1 and not active2 and not active3 and not active4:
break
假设“更高效”,您的意思是“更快:需要分析实际用例以找出哪个版本的运行时间更短。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.