这里完全是蟒蛇初学者。
我有以下函数,它检查从某些输入派生出来的字符串是否存在于文本文件中。它循环遍历文本文件的每一行,以查看是否找到了确切的匹配。
在发现比赛后,我必须立即挣脱圈套,以避免不必要的循环。
以下是代码:
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()我正在寻找一种更简洁的、节奏式的方法来构造代码。我能做些什么让这件事变得更好吗?以某种方式消除了对"DateZoneCity_exists“和第二个If语句的需求?
发布于 2016-06-10 04:28:33
在这种情况下,any是最好的解决方案:
# Function to check if a given DateZoneCity
def DateZoneCity_downloaded_previously(Order_Date, ZoneCity):
# 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:
return any((string_to_match in line) for line in download_status)请注意,在这种情况下,它将返回负的False,而不是返回None的当前实现,还请注意,它在找到正结果时确实会跳出循环,因此它不需要以任何方式循环整个文件。
发布于 2016-06-10 04:20:25
只是return而不是break
def DateZoneCity_downloaded_previously(Order_Date,ZoneCity):
"""Check if a given DataZoneCity combination had already been downloaded."""
string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
with open(Record_File) as download_status:
for line in download_status:
if string_to_match in line:
return True
return False # No match found.发布于 2016-06-10 04:22:24
根据文本文件的大小,您可以将其读入字符串,只需使用它(比每行读取和检查行更容易,而且速度更快):
if string_to_match in open(Record_File).read():
return True在你的例子中:
def DateZoneCity_downloaded_previously(Order_Date,ZoneCity):
string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1]
if string_to_match in open(Record_File).read():
return Truehttps://stackoverflow.com/questions/37739756
复制相似问题