Pythonic打破循环的方式

钦迈·卡马特

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

塔德格·麦克唐纳·詹森

这感觉是一种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,还应注意,在找到正数结果后,它确实会立即退出循环,因此不需要以任何方式循环遍历整个文件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章