Python 网站拦截器中的列表理解

Python List Comprehension in Website Blocker

在第 2 行中,any() 方法从列表理解中获取 'website',然后根据布尔值执行步骤。它工作得很好。但是,如果没有列表理解语法,我不能用基本语法(仅使用 if、for、any、in)​​来写这一行。我知道最好使用列表理解,但这是为了教育。

for line in content:
    if not any(website in line for website in websites):
        file.write(line)

我试过类似的方法,我知道这不会给出正确的结果。

for line in lines:
    for website in websites:
        if any(website):
            print(line)

可在此处找到完整代码:https://github.com/shaanlearn/pypractice/blob/main/websiteBlocker

行号:39-41

您可以按如下方式扩展列表理解

for line in content:
    result = []
    for website in websites:
        result.append(website in line)
    if not any(result):
        file.write(line)

试试这个

for line in lines:
    for website in websites:
        if website in line:
            break
    print(line)

另一种扩展方式:

for line in content:
    for website in websites:
        if website in line:
            break
    file.write(line)