跳出怪圈的Python式方法

2024-10-04 09:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是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语句的需要?在


Tags: to代码intrueifdownloadmatchstatus
3条回答

只需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.

这种情况下,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,还请注意,它确实会在找到一个正结果时立即跳出循环,因此它不需要以任何方式循环整个文件。在

根据你的文本文件有多大,你可以把它读入一个字符串,然后使用它(比每行读取和检查一行更容易,而且通常更快):

if string_to_match in open(Record_File).read():
    return True

在您的例子中:

^{pr2}$

相关问题 更多 >