python - Python中list类的__contains__方法是如何实现的?

标签 python

假设我定义了以下变量:

mode = "access"
allowed_modes = ["access", "read", "write"]

我目前有一个类型检查语句是

assert any(mode == allowed_mode for allowed_mode in allowed_modes)

但是,似乎我可以简单地将其替换为

assert mode in allowed_modes

根据 ThiefMasterPython List Class __contains__ Method Functionality 中的回答,这两个应该是等价的。真的是这样吗?我如何通过查找 Python 的源代码轻松验证这一点?

最佳答案

不,它们不等同。例如:

>>> mode = float('nan')
>>> allowed_modes = [mode]
>>> any(mode == allowed_mode for allowed_mode in allowed_modes)
False
>>> mode in allowed_modes
True

参见 Membership test operations有关更多详细信息,包括此声明:

For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

关于python - Python中list类的__contains__方法是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41956806/

相关文章:

python - 当鼠标悬停在按钮上时,我想为 Maya 中的架子按钮创建文档

python - 格式化日期时间标签以包含 Pandas 图的工作日名称

Python XML 解析器 : junk after document element

python - DNNRegressor 训练输入多个标签

Python的np数组列表到数组

python - 我无法将表从 postgres 填充到 django 模型

python - 在groupby Python后查找配对记录

python - 在 Python 中,有效地确定两个列表是否是彼此的移位副本

python - python类型中的__flags__是做什么用的

python - 修改不同的对象而不检查标志