为了账号安全,请及时绑定邮箱和手机立即绑定

python 中的变量赋值错误

python 中的变量赋值错误

慕哥9229398 2022-08-16 10:33:26
我得到了一个变量赋值错误,显然没有理解一些东西,但从我的代码中,我不明白为什么会发生这种情况。代码:   def something(filename):    with open("tmp/"+filename.stem+".txt", "r") as infile: # opening the tmp file for scraping the data        readfile = infile.readlines() #reads the infile lne by line and returns a list containing the lines        for i, line in enumerate(readfile[1:], 1): # looping over all the lines in the file from position 1 (so skipping 0) to avoid circular feedback            if 'Overview' in line:                start = i                continue                for i, line in enumerate(readfile[1:], 1):                    if 'Identified secondary metabolite regions using strictness' in line:                        end = i                        marker = list(map(lambda s: s.strip('\n'), readfile[start + 1:end])) # stripping the '\n' off every element in the list. map executes a function for each element in a sequence        for i, line in enumerate(readfile[1:], 1): # looping over all the lines in the file from position 1 (so skipping 0) to avoid circular feedback            for location in marker:错误:UnboundLocalError: local variable 'marker' referenced before assignment由于第一个 forloop 在第二个 forloop 之前执行导致被设置,因此不应始终在函数范围内进行赋值?markermarker其次,使用两个for循环似乎很混乱,我如何在一个for循环中执行此操作?
查看完整描述

3 回答

?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

关键是,它是在“如果”条件下分配的。如果它是假的呢?marker



查看完整回答
反对 回复 2022-08-16
?
缥缈止盈

TA贡献2041条经验 获得超4个赞

尝试在函数外部定义标记变量。然后在功能中使用它。

refer-> 不明白为什么 UnboundLocalError 会发生


查看完整回答
反对 回复 2022-08-16
?
忽然笑

TA贡献1806条经验 获得超5个赞

marker在不满足条件时未设置。设置在开头。if 'Identified secondary metabolite regions using strictness' in line:marker = []



查看完整回答
反对 回复 2022-08-16
  • 3 回答
  • 0 关注
  • 286 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号