python - 返回在 if else 语句中分配的递归变量,python中的逻辑问题
问题描述
我目前遇到递归语句的逻辑问题。我的代码如下
def find_postpep_site(string):
if(re.search('(G[RK])|(GKR)|(G$)', string)):
lastindex = (re.search('(G[RK])|(GKR)|(G$)', string)).end()
find_postpep_site(string[lastindex:10000])
else:
return lastindex
输出如下
Traceback (most recent call last):
File "cleavage_test.py", line 47, in <module>
mature = (data[find_pp_site(data):find_postpep_site(data)])
File "cleavage_test.py", line 38, in find_postpep_site
find_postpep_site(string[lastindex:10000])
File "cleavage_test.py", line 38, in find_postpep_site
find_postpep_site(string[lastindex:10000])
File "cleavage_test.py", line 41, in find_postpep_site
return(lastindex)
UnboundLocalError: local variable 'lastindex' referenced before assignment
这个问题并不复杂,但令人沮丧。我想让这个方法自包含,不想在程序主体中初始化和分配一个变量。
所以我的问题是,如何在每次方法递归运行时不重置它的情况下为 lastindex 分配一个值?例如(坏例子)
def find_postpep_site(string):
lastindex = 0
if(re.search('(G[RK])|(GKR)|(G$)', string)):
lastindex = (re.search('(G[RK])|(GKR)|(G$)', string)).end()
find_postpep_site(string[lastindex:10000])
else:
return lastindex
这将始终返回零
谢谢
解决方案
如果lastindex
存在于函数体之外,您可以引用函数顶部的全局变量。lastindex 必须全局存在或通过递归向下传递。记得在你的递归步骤中添加一个 return 语句。见下文:
def find_postpep_site(string):
global lastindex #added
if(re.search('(G[RK])|(GKR)|(G$)', string)):
lastindex = (re.search('(G[RK])|(GKR)|(G$)', string)).end()
return find_postpep_site(string[lastindex:10000])
else:
return lastindex
推荐阅读
- python - Ansible + Jinja2 Loop - Dict 对象没有属性
- quarkus - quarkus 2.1.1.Final ClassNotFoundException:io.netty.util.concurrent.FastThreadLocal
- c# - ASP.NET MVC:如何从枚举中禁用选择列表项
- javascript - 如何使输入与输入匹配计数器像 ctrl+f 一样?
- php - PHP | 只有变量应该通过引用传递 | 为什么老版本没有这个错误?
- javascript - WebRTC 数据通道不适用于多连接
- javascript - 相对 URL 重定向
- bloomberg - 当通过 cscript.exe 启动 excel 时,bloomberg api 刷新不起作用
- python - 我要绘制图表,但我遇到了问题。使用其他变量我可以绘制但使用变量名称“温度”我收到错误
- python-3.x - 将 Python 记录器配置为仅在某些特殊情况下写入文件?