python里的return用在循环里_Python-如何在for循环中使用return语句?

在循环中使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值