我有以下功能:
def in_loop(i):
global loop_started
if i == '[':
loop_started = True
return [True,'loop starting']
if loop_started:
if i == ']':
loop_started = False
return [True,'loop over']
return True
return False
我相信这将返回一个元组,当我为“]”时,该元组看起来像(真,“循环”).
然后,我尝试用
for index,i in enumerate(code):
if in_loop(i):
loop_counter += 1
if in_loop(i)[1] == 'loop starting':
loop_start = index
if in_loop(i)[1] == 'loop over':
loops[f'loop{loop_num}'] = {'start': loop_start,'end': index}
loop_num += 1
但这会引发错误
TypeError: 'bool' object is not subscriptable
另外,代码=“ [-] [-]”.
在索引到元组时为什么会引发此错误?
最佳答案
问题是当到达像”或’-‘之类的字符时,您实际上返回的是布尔值,但是如果in_loop(i)[1] ==’循环开始’,则仍在访问:尽管如此.
原文链接:https://www.f2er.com/python/533257.html您必须返回一致的返回类型,第二个for循环代码才能正常工作.对于前者,请查看以下代码注释:
def in_loop(i):
global loop_started
if i == '[':
loop_started = True
return [True,'loop starting']
if loop_started:
if i == ']':
loop_started = False
return [True,'loop over']
return True #This will have side effects and is inconsistent with your other returns of in_loop
return False #This will have side effects and is inconsistent with your other returns of in_loop