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 Else如果您希望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循環使用其他流量控制?
found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print 'No object found.'
如果你在if循環中有一個斷點的if語句(除非你有'if 1 == 2:1'之類的東西),你不能保證你的循環將總是完成。你當然可以*總是*用'else'從句去掉。然後,「找不到對象」。將始終打印,不論是否找到了匹配的關鍵字都不會馬上出現。 – Evert 2015-01-20 19:38:51
你的問題似乎不清楚;你問題的大背景是什麼?你總是使用'else'子句來達到什麼目的? – Evert 2015-01-20 19:39:38
如果你總是希望你的循環運行到完成,那麼你可能不希望循環中有任何'break'語句。如果循環中沒有'break'語句,那麼具有'else'構造的點對我來說就不清楚了。 – rchang 2015-01-20 20:03:19