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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

yuanteng8   2021-05-17 我要评论
想了解python3 怎样使用 goto 跳转执行到指定代码行的相关内容吗,yuanteng8在本文为您仔细讲解python3 goto跳转指定代码行的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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完成一个小例子

官方文档见:http://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 下有红色波浪线提示错误。不用理会直接执行即可

补充:Pycharm跳转回之前所在的代码行

用Pycharm写Python代码有一段时间了,有一个问题一直困扰着我:浏览代码的时候时常需要从一个函数跳转到另一个函数,有时候两个函数相聚比较远,我一直不知道怎么直接回到上一个函数。

于是我采取的办法是按ctr+F然后输入上一个函数的函数名来定位并且回到上一个函数。不忍直视~~~

下面是找到跳转按钮的过程:

1.找到View下面的Toolbar并勾选上

SouthEast

2.按钮出现

SouthEast

一款对浏览代码功能支持良好的IDE一般Toolbar上都有按钮或者会有快捷键可以在历史浏览页面之间跳转。而我的Pycharm的默认设置一直是将Toolbar隐藏起来的。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们