这里是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()
我正在寻找一种更简洁的python方式来构造代码。有什么我能做的吗?以某种方式消除对“DateZoneCity_exists”和第二个If语句的需要?在
只需
return
而不是break
:这种情况下,
any
是最佳解决方案:注意,在本例中,它将返回
False
,而不是您当前的实现,它将返回None
,还请注意,它确实会在找到一个正结果时立即跳出循环,因此它不需要以任何方式循环整个文件。在根据你的文本文件有多大,你可以把它读入一个字符串,然后使用它(比每行读取和检查一行更容易,而且通常更快):
在您的例子中:
^{pr2}$相关问题 更多 >
编程相关推荐