python raise stopiteration_迭代列表并精美地处理Python中的StopIteration

我试图遍历列表,我需要在迭代到达列表末尾时执行特定操作,请参阅下面的示例:

data = [1, 2, 3]

data_iter = data.__iter__()

try:

while True:

item = data_iter.next()

try:

do_stuff(item)

break # we just need to do stuff with the first successful item

except:

handle_errors(item) # in case of no success, handle and skip to next item

except StopIteration:

raise Exception("All items weren't successful")

我相信这段代码不太Pythonic,所以我正在寻找更好的方法.我认为理想的代码应该看起来像下面的假设:

data = [1, 2, 3]

for item in data:

try:

do_stuff(item)

break # we just need to do stuff with the first successful item

except:

handle_errors(item) # in case of no success, handle and skip to next item

finally:

raise Exception("All items weren't successful")

欢迎任何想法.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值