未索引到 bool 时出现“bool 不可下标”错误 - Python

我有以下功能:


    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

我相信当我是“]”时,这会返回一个看起来像 (True, 'loop over') 的元组。然后我尝试将其编入索引


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

另外,代码 = "+++++[-][-]"。


为什么在索引元组时会引发此错误?


绝地无双
浏览 206回答 3
3回答

aluckdog

问题是,当到达像“+”或“-”这样的字符时,您实际上是在返回布尔值,但if in_loop(i)[1] == 'loop starting':仍然在访问。您必须返回一致的返回类型才能使第二个 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

慕村225694

这种情况只有当你输入的东西是不是'['还是']',因为它会到了第二if的if loop_started:,并且默认如果内部条件不及格,那就只是return True,所以这就是为什么它不工作。

慕田峪9158850

你将 var 初始化loop_started为什么?(或者换句话说,loop_started当函数没有被执行时有什么价值?)如果loop_started是False在函数执行之前,则函数将直接返回 False。一个快速的解决方法是在所有布尔返回语句之后添加一个空字符串。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python