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

2024-05-08 19:02:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个递归函数来遍历加载到python dict的JSON字符串,当我在JSON结构中找到最终所需的键时,我试图停止。我在那个地方有一个明确的break语句,但它似乎不是break。我不明白为什么会这样。我已经包括了下面的输出,但这是一个工作python2的例子。我将示例JSON字符串放在一个gist中。你知道吗

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'])

输出,在“i make it”和打印值之后应该会中断,但它会继续:

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

Tags: andthekeyjsonleniskeysdict
2条回答

问题来自这个块,在这里递归调用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。在everyfor循环中插入语句if done : break,这将很快打破它们。你知道吗

相关问题 更多 >