Python *list* "in"运算符 : equality, 哈希检查,还是身份?

标签 python operators contains

评论中的人要求我提供实际的代码,所以我删除了旧的示例。

我正在制作this ,并且我希望两个具有相同标题的 Page 比较相等。我已经对 Page 类执行了此操作:

def __eq__(self, other):
    return self.title == other.title

但如果我这样做,那就不是真的:

>>> import mw_api_client as mwc
>>> w = mwc.Wiki('https://en.wikipedia.org/w/api.php')
>>> a = [w.page(str(i)) for i in range(20)]
>>> w.page('0') in a
False

我怎样才能做到这一点?

最佳答案

列表的 __contains __ 方法记录在“成员资格测试”部分中:

https://docs.python.org/3.6/reference/expressions.html#membership-test-details

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).

对于您的特定用例,您需要覆盖 __contains__ - 但是您不能只覆盖列表上的 __contains__ - 例如:

a = []
a.__contains__ = lambda: True
AttributeError: 'list' object attribute '__contains__' is read-only

因此,解决方案是创建一个包装列表的自定义类,并提供它自己的 __contains__ 方法。类似以下内容(请注意,我使用的是字典,因此在此示例中使用 obj['title'] 而不是 obj.title - 您可能还想测试更多内容在 __contains__ 中,例如类型比较等)。我在这里使用 UserList ,因为它提供了一个很好的 list 类来继承,并使列表内容在 data 中可用:

from collections import UserList

class MyList(UserList):
    def __init__(self, lst):
        self.data = lst

    def __contains__(self, obj):
        """Return True if any item in the list has a title, and the title matches that of the passed-in dict"""
        return any(obj['title'] == x['title'] for x in self.data if 'title' in x)

mr = {"title": "mr"}
mrs = {"title": "mrs"}
dr = {"title": "dr"}
random = {"foo": "bar"}


x = [mr, mrs, random]

y = MyList(x)

print(mr in y) # True
print(dr in y) # False
y.append(dr)
print(dr in y) # True

关于Python *list* "in"运算符 : equality, 哈希检查,还是身份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48850824/

相关文章:

javascript - 我将如何扩展 JavaScript 语言以支持新的运算符?

python - 检查字典键是否包含任何另一个字典的键并打印匹配对

JSON 架构 : How to check that an array contains at least one object with a property with a given value?

python - pip install -r pip-requires 与 setup.py install 之间的区别

python - Dash 交互式图表不会从 Pandas Dataframe 更新

python - 是否可以编写一个 BigQuery 来检索 PyPI 下载随时间的分箱计数?

python - 在 Python 中以 1 个折线图显示基于 2 个非数值数据和一个数值数据的数据

c++ - 我需要手动声明 >= 和 <= 运算符吗?

c# - 为什么 Postfix++/-- 在 C# 中被归类为主要运算符?

c# - 如果 T 是类或结构,则在 ConcurrentQueue 中使用 Contains<T> 方法