【问题标题】:all( generator ) returns True when it should return Falseall( generator ) 在应该返回 False 时返回 True
【发布时间】:2023-03-26 06:39:01
【问题描述】:

我想检查一个字符串是否包含所有关键字。我正在使用Enthought Canopy 分发版。

例如:

string  = 'I like roses but not violets'
key_words = ['roses', 'violets', 'tulips']

我听说all 函数对我很有帮助。当我通过以下方式使用此功能时

if all( keys in string.lower().split() for keys in key_words):
    print True

然后返回True

我希望False 会被返回,因为tulips 不在string.lower().split() 中。

我该如何解决这个问题?

【问题讨论】:

  • 无法重现 - 我收到 False
  • 我也返回 false,你确定你没有这样做 - if not all( keys in string.lower().split() for keys in key_words) 或使用 any() 吗?
  • 在你的 if 语句之前添加这一行:from __builtin__ import all,看看是否有帮助。

标签: python numpy generator canopy


【解决方案1】:

您的代码中可能有一个from numpy import *numpyall 方法不能很好地处理生成器。

[1]: string  = 'I like roses but not violets'

[2]: key_words = ['roses', 'violets', 'tulips']

[3]: if all( keys in string.lower().split() for keys in key_words):
         ...:         print True
         ...:

[4]: from numpy import *

[5]: if all( keys in string.lower().split() for keys in key_words):
        print True
         ...:
True

如果上下文超出您的控制范围,您可以使用from __builtin__ import allall 恢复为文件中的默认版本。但是,推荐的方法是对numpy 进行选择性或合格导入。

【讨论】:

  • 哦,可能是这样。我在 Enthought Canopy 工作。谢谢
  • 尽可能使用官方发行版,注意不要做掩码内置函数之类的事情。
  • 会的。感谢您的建议。
猜你喜欢
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多