python - 如何将 bool 条件包含到Python的列表理解中?

标签 python string list-comprehension boolean-logic

输入: 我有一个字符串列表,其中包含我可以工作的地方:

ALL_CHANCES = ['I can work in China',
               'I can work in Germany',
               'I can work in Singapore',
               'I can work in Norway']

我还有另一个字符串列表,其中包含最好不要工作的地方:

HIGH_TAX = ['Germany',
            'Norway']

输出: 我正在寻找一种简单的列表理解单行代码来过滤列表 1 中包含列表 2 中出现的子字符串的项目:

GOOD_CHANCES = ['I can work in China',
                'I can work in Singapore']

挑战:

但是,当我这样做

GOOD_CHANCES  = [item for item in ALL_CHANCES
                      if (not any(word for word in HIGH_TAX) in item)]

我产生以下错误:

'<string>' requires string as left operand, not bool 

如何将 bool 条件包含到Python的列表理解中?

最佳答案

您可以按如下方式更简单:

GOOD_CHANCES  = [item for item in ALL_CHANCES \
                  if not any(word in item for word in HIGH_TAX)]

在您的解决方案中,not any(HIGH_TAX 中逐字逐句) 正在计算为 bool,然后将其与字符串 item 进行比较>。相反,如上所示,您可以在 any 方法调用本身中包含子字符串检查

使用 filter 方法可能会更清晰:

filter(lambda item: not any(word in item for word in HIGH_TAX), ALL_CHANCES)

关于python - 如何将 bool 条件包含到Python的列表理解中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50363046/

相关文章:

python - 为什么我的 setup.py 生成的脚本找不到我还安装的模块?

python - 计算行数并根据字符串 [with str.contains] 在 python 中的位置创建标签列

java - 在框架中画一根绳子。

java - 在java中查找括号字符串的有效性

Python:为什么列表理解比for循环慢

python - 回归模型中成本函数的 L1 范数而不是 L2 范数

Python:仅使用列表中尚未存在的值更新 dict[key] 值列表

python - "unit tests have failed"for beautifulsoup

javascript - 将数组理解转换为 `map` 和 `filter`

python - 从 python 中的理解返回多个列表