如何将布尔条件包含到 python 的列表理解中?

How to include boolean conditions to python's list comprehension?

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

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 

如何将布尔条件包含到 python 的列表理解中?

你可以做的更简单:

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

在您的解决方案中,not any(word for word in HIGH_TAX) 评估为 bool,然后将其与字符串 item 进行比较。相反,如上所示,您可以在 any 方法调用本身

中包含子字符串检查

使用filter方法可能也更清楚:

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

最简单的方法是:

[item for item in ALL_CHANCES if item.split()[-1] not in HIGH_TAX]

这是假设所有国家都在句子的末尾。

如果这个国家可能存在于任何地方,你可以试试:

[item for item in ALL_CHANCES if not any( h in item for h in HIGH_TAX )  ]