I was looking at this SO question about the Python For Else flow control and I thought I had a portion of code that which is very close to the example given.我认为我的代码非常接近示例代码,除了我希望for循环完成(用于记录目的)。
for module_name, class_name in BASIC_PARSERS_TO_RUN:
full_module_name = "parsers." + module_name
parser = getattr(import_module(full_module_name), class_name)(
logger=logger)
parser_data = parser.parse(cluster_path)
if parser_data is None or parser_data == "0":
# Basic None instead of "None" so that json is serialized to null
# instead of "None"
json_data_list.append({module_name: parser_data})
failed_basic_checks = True
else:
json_data_list.append({module_name: str(parser_data)})
# Checking if we have a valid data set.
if failed_basic_checks:
json_data_list.append({"basic_validation_succeeded": False})
return json.dumps(json_data_list)
# We've run into a dataset which isn't valid.
exit(1)
有没有办法改变我的for循环以使用for else流量控制?
found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print 'No object found.'
答案 0 :(得分:2)
编写的代码很好;我没有理由使用for
/ else
结构。
根据the docs,除非循环被else
语句终止,否则总是执行循环之后的break
。因此,如果您不在循环中使用break
语句,则不需要else
子句;你应该简单地把相关的代码放在循环之后。