首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >勾股跳出回路

勾股跳出回路
EN

Stack Overflow用户
提问于 2016-06-10 04:12:17
回答 5查看 1.3K关注 0票数 6

这里完全是蟒蛇初学者。

我有以下函数,它检查从某些输入派生出来的字符串是否存在于文本文件中。它循环遍历文本文件的每一行,以查看是否找到了确切的匹配。

在发现比赛后,我必须立即挣脱圈套,以避免不必要的循环。

以下是代码:

代码语言:javascript
复制
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()

我正在寻找一种更简洁的、节奏式的方法来构造代码。我能做些什么让这件事变得更好吗?以某种方式消除了对"DateZoneCity_exists“和第二个If语句的需求?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-06-10 04:28:33

在这种情况下,any是最好的解决方案:

代码语言:javascript
复制
# 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的当前实现,还请注意,它在找到正结果时确实会跳出循环,因此它不需要以任何方式循环整个文件。

票数 6
EN

Stack Overflow用户

发布于 2016-06-10 04:20:25

只是return而不是break

代码语言:javascript
复制
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.
票数 4
EN

Stack Overflow用户

发布于 2016-06-10 04:22:24

根据文本文件的大小,您可以将其读入字符串,只需使用它(比每行读取和检查行更容易,而且速度更快):

代码语言:javascript
复制
if string_to_match in open(Record_File).read():
    return True

在你的例子中:

代码语言:javascript
复制
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
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37739756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档