Pythonic打破循环的方法

Chi*_*mat 4 python loops python-3.x

总蟒蛇初学者在这里.

我有以下函数,它检查文本文件中是否存在从某些输入派生的字符串.它遍历文本文件的每一行,以查看是否找到了完全匹配.

我必须在找到匹配后立即退出循环,以避免不必要的循环.

这是代码:

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()
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种更简洁,更pythonic的方式来构造代码.有什么办法可以让它变得更好吗?以某种方式消除了对"DateZoneCity_exists"和第二个If语句的需求?

Tad*_*sen 6

这感觉就像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)
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,它将返回False负数而不是将返回的当前实现None,还要注意它在找到肯定结果时立即突破循环,因此它不需要以任何方式循环遍历整个文件.