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

时间:2018-07-08 07:46:52

标签: python json recursion break

我编写了一个递归函数来遍历加载到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

2 个答案:

答案 0 :(得分:1)

问题来自此块,您在其中递归调用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

答案 1 :(得分:0)

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

请谨慎使用递归=)

您可以创建全局标记done,将其设置为False,然后在找到所需内容后将其设置为True。在每个 for循环中,插入语句if done : break-这将很快破坏一切。