做出决定后循环停止

时间:2018-10-18 01:05:49

标签: python

例如,我在下面的输入中使用了循环函数来循环字典列表中的每个元素:

代码:

a =[[{"new":[{"name":"rule"}]}, {"new":[{"name":"king"}]}, {"find":"thanks"}, {"nothing":"cool"}]]
for x in a:
    for xx in x:
        if any(xxx["name"] == "rule" for xxx in xx.get("new", [])):
            try:
                print(["success"])
            except:
                print(["fail"])

Below is just an example of the real dataset output after returning all the thing. It is not `["success"]` or `["fail"]` because this is just an example to show what my problem in the code.


["something"]
["nothing"]
["just"]
["for"]
None
None
["showing"]
None
["example"]

I understand that since the json file has no "new" key for certain dictionaries so it will return None. But I would Like to replace this None to string "Not Found". I tried many methods to modify my code but always the return will become very weird. 

我尝试了以下代码:

for x in a:
    for xx in x:
        if xx.get("new") is None:
            return ["Not getting"]
        if any(xxx == "name" for xxx in xx.get("new", [])):
            try:
                return["success"]
            except:
                return["fail"]

我的回报是

["Not getting"]
["Not getting"]
["Not getting"]
["Not getting"]
["Not getting"]
["Not getting"]
["Not getting"]
["Not getting"]

即使字典中有"new"

1 个答案:

答案 0 :(得分:0)

您的代码正在执行您要告诉的内容。 return表示返回。您可能会尝试先跑步,然后才能走路,但这是我对您尝试做的最好的解释。请注意,使用尽可能有意义的名称-命名变量确实可以为您提供帮助。

a = [[{"new": "name"}, {"new": "king"}, {"find": "thanks"}, {"nothing": "cool"}]]


def loop_example(list_of_lists_of_dict):
    for list_of_dict in list_of_lists_of_dict:
        for dictionary in list_of_dict:
            if "name" == dictionary.get("new", []):
                print("success for {}".format(dictionary))
            else:
                print("fail for {}".format(dictionary))

# loop_example(a) yields:
# success for {'new': 'name'}
# fail for {'new': 'king'}
# fail for {'find': 'thanks'}
# fail for {'nothing': 'cool'}


# As a comprehension
def comprehension_example(list_of_lists_of_dict):
    return [("success" if "name" == dictionary.get("new") else "fail")
            for list_of_dict in list_of_lists_of_dict for dictionary in list_of_dict]

# comprehension_example(a) yields:
# ['success', 'fail', 'fail', 'fail']