在循环中使用return将中断它并退出方法/函数,即使迭代仍未完成。
例如:def num():
# Here there will be only one iteration
# For number == 1 => 1 % 2 = 1
# So, break the loop and return the number
for number in range(1, 10):
if number % 2:
return number
>>> num()
1
在某些情况/算法中,如果满足某些条件,我们需要中断循环。但是,在当前代码中,在完成循环之前中断循环是一个错误/错误的设计。
相反,您可以使用不同的方法:
生成数据:def show_todo():
# Create a generator
for key, value in cal.items():
yield value[0], key
你可以这样称呼它:a = list(show_todo()) # or tuple(show_todo()) and you can iterate through it too.
将数据追加到临时列表、元组、dict或字符串中,然后在循环退出后返回数据:def show_todo():
my_list = []
for key, value in cal.items():
my_list.append([value[0], key])
return my_list