繁体   English   中英

为什么我的python循环没有中断?

[英]Why is my python loop not breaking?

我编写了一个递归函数,以遍历加载到python dict的JSON字符串。 当我在JSON结构中找到最终所需的键时,我试图停止。 我在那个地方明确地有一个break语句,但似乎没有中断。 我为此感到困惑。 我已经在下面包含了输出,但这是一个有效的python2示例。 我将示例JSON字符串放入了要点。

import urllib2
import json

# This is loading the JSON
url ="https://gist.githubusercontent.com/mroth00/0d5c6eb6fa0a086527ce29346371d8ff/raw/700d28af12184657eabead7542738f27ad235677/test2.json"
example = urllib2.urlopen(url).read()
d = json.loads(example)

# This function navigates the JSON structure
def j_walk(json_input,dict_keys):
    for key, values in json_input.items():
        #print(index)
        if (key != dict_keys[0]):
            print("passing")
            print(key)
            continue
        elif ((key == dict_keys[0]) and (len(dict_keys)>1) and (values is None)):
            return 'missingValue'
        elif ((key == dict_keys[0]) and (len(dict_keys)==1) and (values is None)):
            return 'missingValue'
        elif ((key == dict_keys[0]) and (len(dict_keys)==1)):
            print(key)
            print(dict_keys[0])
            print(len(dict_keys))
            print("i made it")
            print values
            break
        elif ((key == dict_keys[0]) and (len(dict_keys)>1)):
            print(len(dict_keys))
            #print(values)
            j_walk(values,dict_keys[1:])
        else:
            return 'somethingVeryWrong'

# Run the function here:
j_walk(d,['entities','hashtags'])

输出,它应该在“我成功”并打印值之后中断,但它会继续运行:

passing
user
passing
truncated
passing
text
passing
created_at
2
passing
symbols
passing
user_mentions
hashtags
hashtags
1
i made it
[{u'indices': [103, 111], u'text': u'Angular'}]
passing
id_str
passing
id
passing
source

问题来自此块,您在其中递归调用j_walkbreak语句仅停止此递归,然后初始循环继续:

elif ((key == dict_keys[0]) and (len(dict_keys)>1)):
    print(len(dict_keys))
    j_walk(values,dict_keys[1:]) # beginning of a second loop

    #You need some break here to stop this evil loop
    break

break打破了for循环,但没有递归调用j_walk()函数。

请谨慎使用递归=)

您可以创建一个done的全局标志,将其设置为False ,然后在找到所需内容后将其设置为True if done : break ,则在每个 for循环内插入以下语句if done : break这将迅速破坏所有内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM