输入: 我有一个字符串列表,其中包含我可以工作的地方:
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/