python - 如何在 Python 中为 "in"关键字指定自定义比较器?

标签 python python-2.7 python-2.x

我是 Python 的新手,所以我欢迎其他方法。

我有一个字典列表(从文件中读取)。 现在我有一堆额外的词典,我想添加到这个列表中,但前提是它们不在原始列表中。

但是,我要求“不在原始列表中”由自定义比较函数定义,而不是 Python 默认使用的任何内容。

更具体地说,我想比较字典中的某些键/值对,如果它们相同,则为表达式返回“true”。

myList = ReadFromFile...
newList = ReadFromFile...
for item in newList:
    if item not in myList: #I want custom behavior for this "in"
        myList.append(item)

最佳答案

使用any :

any(customEquals(item, li) for li in myList)

如果myClass是你可以控制的类型,你也可以覆盖__contains__方法。

关于python - 如何在 Python 中为 "in"关键字指定自定义比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9898617/

相关文章:

iterator - Python 中的可迭代性

python - 从python中的函数返回错误字符串

python - 什么是 Python 2.x 数据库接口(interface)?

python - 在 shell 脚本中读取用户输入

python - 如何根据最近的日期合并两个数据框

python - Moto模拟lambda发布SNS

python - python 中是否有 chgrp -R 的等效项?

python - 如何在网页中连续显示python输出?

python - 如何防止 C 共享库在 python 的标准输出上打印?

python - 我设置了 True=False 并且我无法撤消它