You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python列表推导式中加入布尔条件?

如何在Python列表推导式中正确使用布尔条件过滤元素?

你想要从ALL_CHANCES列表里过滤掉包含HIGH_TAX中任意地点的字符串,这个思路没问题,但你的列表推导式里布尔条件的逻辑顺序写错了,才导致了类型错误。

先看看你出错的代码:

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

这里的问题出在any(word for word in HIGH_TAX)——这个表达式会直接返回True(因为HIGH_TAX是非空列表,any()只要迭代器里有元素就返回True),之后你写的not True in item就变成了False in item。而item是字符串,Python没法判断布尔值False是否属于字符串,这就是你看到'<string>' requires string as left operand, not bool错误的核心原因。

正确的逻辑应该是先检查每个地点是否在当前item里,再用any()判断是否有匹配,最后对结果取反,也就是把word in item放到any()的生成器表达式里。

正确的列表推导式代码

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

逻辑解释

  1. 遍历ALL_CHANCES中的每一个item字符串
  2. 对每个item,逐一检查HIGH_TAX里的地点是否是item的子串
  3. any()会在有任意一个地点匹配时返回True,我们用not取反,只有当没有任何地点匹配时,才将这个item加入结果列表

代入你的测试数据验证:

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']
GOOD_CHANCES = [item for item in ALL_CHANCES if not any(word in item for word in HIGH_TAX)]
print(GOOD_CHANCES)
# 输出: ['I can work in China', 'I can work in Singapore']

完全符合你想要的结果。

内容的提问来源于stack exchange,提问作者sudonym

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:52:55