Python的“if not in”有问题

2024-05-16 08:55:06 发布

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

我正在写下面的代码,并且面临一个令人沮丧的问题,在被困了两天之后我还没能解决它。你知道吗

这是简化代码:

def crawl_web(url, depth):
    toCrawl = [url]
    crawled = ['https://index.html']
    i = 0
    while i <= depth:
        interim = []
        for x in toCrawl:
            if x not in toCrawl and x not in crawled and x not in interim:
                print("NOT IN")
            crawled.append(x)
        toCrawl = interim
        i += 1
    return crawled

print(crawl_web("https://index.html", 1))

我预期的结果应该是:

['https://index.html']

但不知怎的,“如果不在”不起作用,一直给我这个作为输出:

['https://index.html','https://index.html']

Tags: and代码inhttpsweburlindexhtml
1条回答
网友
1楼 · 发布于 2024-05-16 08:55:06

无论if语句做什么,都会调用crawled.append,因为它与if语句处于同一缩进级别。你得把它移进去。你知道吗

def crawl_web(url, depth):
    toCrawl = [url]
    crawled = ['https://index.html']
    i = 0
    while i <= depth:
        interim = []
        for x in toCrawl:
            if x not in toCrawl and x not in crawled and x not in interim:
                print("NOT IN")
                crawled.append(x)
        toCrawl = interim
        i += 1
    return crawled

print(crawl_web("https://index.html", 1))

相关问题 更多 >