【问题标题】:Python List Comprehension in Website Blocker网站拦截器中的 Python 列表理解
【发布时间】:2021-10-01 13:36:46
【问题描述】:

在第 2 行,any() 方法从列表推导中获取“网站”,然后根据布尔值采取步骤。它工作得很好。但是,如果没有列表理解语法,我无法用基本语法(仅使用 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

【问题讨论】:

  • 那么问题是什么

标签: python list-comprehension any


【解决方案1】:

你可以扩展列表理解如下

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

【讨论】:

  • 嗨@pranta-palit,感谢您的快速回复,这个成功了!不过我有一个问题,当我打印结果列表时,它给出了布尔值。像这样:` [False] [False, False] [True] [True, False] [True] [True, True] `
  • result 是一个包含布尔查询的列表,因为我们查询列出的任何网站是否符合要求。这就是 result 包含这些布尔值的原因。然后,如果您应用any() 方法,如果布尔列表中的任何一项为真,它将返回真,同样,如果布尔列表中的任何一项为真,这意味着该行中存在一个或多个网站,则不会写入该行在文件中,如果该行不包含列出的网站,则该行将写入文件。
【解决方案2】:

另一种扩展方式:

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

【讨论】:

  • 当第一个循环遍历content时,我们每次都得到一个新行并检查是否存在任何网站(在网站中),如果不存在则将行写入文件.
【解决方案3】:

试试这个

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

【讨论】:

  • 打印行应该缩进一步
  • @PrantaPalit 感谢您的关注。
猜你喜欢
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
相关资源
最近更新 更多