python - python中的变量赋值错误
问题描述
我收到一个变量分配错误,显然我不理解某些东西,但从我的代码中我看不出它为什么会发生。
编码:
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
marker
由于第一个forloop在第二个forloop之前执行导致marker
被设置,不应该总是在函数范围内分配吗?
其次,使用两个 for 循环似乎很麻烦,我怎样才能在一个 for 循环中做到这一点?
解决方案
关键是marker
在“如果”条件下分配。如果是假的怎么办?
推荐阅读
- javascript - 将 JS 注入 WKWebview
- javascript - 发送表单前的安全问题 - nodejs
- android - 如何从绝对路径获取内容 URI?
- c# - 数据表插入到sql server数据库的双记录
- ios - 'UIActivityIndicatorViewStyleWhiteLarge' 在 ios 13 中已弃用
- c++ - 无法通过 D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX 共享 D3D11_USAGE_STAGING 资源
- python - 为什么我无法在熊猫中获得正确的掩码列
- data-structures - 将平衡二叉树复制到具有最小旋转的 AVL 树的最佳“顺序”遍历
- robot - 通用机器人 TCP/IP 通信:无法发送 crlf ("\r\n")
- python - 尝试在指定路径中制作自复制文件