【问题标题】:Pythonic way to break out of loopPythonic 打破循环的方法
【发布时间】: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 语句的需要?

【问题讨论】:

标签: python loops python-3.x


【解决方案1】:

这感觉就像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 的当前实现,另请注意,它会在找到正数结果后立即跳出循环,因此不需要循环以任何一种方式遍历整个文件。

【讨论】:

  • 不错。非常简洁,非常感谢。
【解决方案2】:

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

【讨论】:

  • 哦,据我了解,return 语句也会立即完成突破,避免未来的循环,对吗?
【解决方案3】:

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

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 True

【讨论】:

    【解决方案4】:

    你不必在此处放置 for 循环,请参阅更新后的代码。

    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:
            if string_to_match in download_status.read():
                return True
        return False  # No match found.
    

    【讨论】:

    • 我担心如果没有 for 循环,整个文件将被加载,并且会占用大量 RAM。没有?
    • 是的,但如果它是一个小文件。无需添加 for 循环。
    【解决方案5】:

    如果record_file 很小,那么你可以直接使用inifstatement,比如:-

    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 True  
    

    如果 record_file 很大,那么您必须遍历每一行以找到匹配项,例如:-

    def DateZoneCity_downloaded_previously(Order_Date, ZoneCity):
        string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0]  + "-" + ZoneCity[1]
        with open(Record_File) as download_status:
            return is_empty((string_to_match in line) for line in download_status)  
    

    因为逐行读取会节省用于保存行的存储空间。

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2012-10-04
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 2013-06-09
      • 1970-01-01
      • 2017-08-17
      相关资源
      最近更新 更多