python3 使用 goto 跳转执行指定代码行

1. 缘起

在实际开发中遇到这样一个问题:
以下是伪代码

if embedding.model is not exist:
	calculate embedding   ## moudel_1
	save embedding.model
else :
	embedding = load embedding.model

try:
	use embedding
except KeyError:
	calculate embedding    ##这里与moudel_1一致。

发现except 中需要粘贴之前写过的calculate embedding
简单概括就是:

somecode_1
try:
	somecode_2
except:
	somecode_3   
	somecode_1   ## 重新执行

2. 使用goto

(1)安装goto

pip install goto-statement

(2)使用goto完成一个小例子

官方文档见:https://pypi.org/project/goto-statement/
定义函数

from goto import with_goto

@with_goto     #必须有
def test(list_):	
    tmp_list = list_
    label.begin		#标识跳转并开始执行的地方
    result = []
    try:
        for i, j in enumerate(list_):
            tmp = 1 / j
            result.append(tmp)
            last_right_i = i
    except ZeroDivisionError:
        del tmp_list[last_right_i + 1]
        goto.begin      #在有跳转标识的地方开始执行
    return result

运行

a = test([1, 3, 4, 0, 6])
print(a)

结果

[1.0, 0.3333333333333333, 0.25, 0.16666666666666666]

注意:如果你在ide山运行label 和 goto 下有红色波浪线提示错误。不用理会直接执行即可

  • 6
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值