【发布时间】:2016-10-10 22:06:03
【问题描述】:
这里是python初学者。
我有以下函数,它检查从某些输入派生的字符串是否存在于文本文件中。它循环遍历文本文件的每一行,以查看是否找到了完全匹配的内容。
我必须在找到匹配项后立即跳出循环,以避免不必要的循环。
代码如下:
def DateZoneCity_downloaded_previously(Order_Date,ZoneCity): # function to check if a given DateZoneCity
# combination had already been completely downloaded
string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
with open(Record_File) as download_status:
DateZoneCity_exists = False
for line in download_status:
if string_to_match in line:
DateZoneCity_exists = True # if match found, then set "DateZoneCity_exists" to True
break # and break out from the [for line in download_status:] loop
if DateZoneCity_exists: return True
download_status.close()
我正在寻找一种更简洁、pythonic 的方式来构建代码。我能做些什么来让这变得更好吗?以某种方式消除对“DateZoneCity_exists”和第二个 If 语句的需要?
【问题讨论】:
-
这属于code review。
-
对不起,我应该做点什么吗?我应该移动线程,但我不知道如何。
-
@Chinmay 以下是一些您可能需要考虑的帖子:A guide to Code Review for Stack Overflow Users 和 Be careful when recommending Code Review to askers
-
download_status.closed最后在做什么? -
你的网上例子是错误的。离开
with块时,download_status将自动关闭——这就是使用with块的意义所在。
标签: python loops python-3.x