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

Python中in运算符逻辑疑问:JS开发者转ML学习的困惑

为什么True in [1,2,3,4]返回True?

这是Python布尔类型的特性导致的,并非in运算符的异常行为:

  • Python里的bool类型是int的子类,True本质上等价于整数1,False等价于整数0。
  • 当使用in运算符检查元素是否存在时,Python会逐个用==判断列表元素和目标值是否相等,而非检查是否为同一个对象(那是is的作用)。

对应你的例子:

  • 对于this_list = [1,2,3,4],True == 1的结果为True,所以in会判定列表中存在匹配元素,返回True。
  • 对于["bananas", "apples"],列表里的字符串和True(即1)用==比较时均不相等,因此返回False。

你可以用以下代码验证这个逻辑:

print(True == 1)  # 输出: True
print(False == 0) # 输出: True
print(isinstance(True, int)) # 输出: True

如果需要严格检查布尔值True是否在列表中(排除整数1的干扰),可以结合类型判断:

this_list = [1,2,3,4, True]
any(isinstance(item, bool) and item is True for item in this_list) # 输出: True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:25:58