将cmp函数或键函数传递给python 2.7中的Set差值(或其他设置操作)

Jul*_*ues 1 python set

我需要在python元组中做一组设置差异,但差异需要考虑我的元组的第一个元素.

为了达到这个目的,我(不经意地)使用了这种类方法

class Filedata(object):
    def __init__(self, filename, path):
        self.filename = filename
        self.path = path + '\\' + filename
    def __eq__(self, other):
        return self.filename==other.filename
    def __ne__(self, other):
        return self.filename!=other.filename
    def __call__(self):
        return self.filename
    def __repr__(self):
        return self.filename     
Run Code Online (Sandbox Code Playgroud)

在sets.py模块中挖掘我发现库使用itertools.ifilterfalse函数来区别对待

def difference(self, other):
    """Return the difference of two sets as a new Set.

    (I.e. all elements that are in this set and not in the other.)
    """
    result = self.__class__()
    data = result._data
    try:
        otherdata = other._data
    except AttributeError:
        otherdata = Set(other)._data
    value = True
    for elt in ifilterfalse(otherdata.__contains__, self):
        data[elt] = value
    return result
Run Code Online (Sandbox Code Playgroud)

但我无法对此做任何有用的事情.

Ign*_*ams 5

要做到这一点的唯一方法是定义只使用第一个元素在你自己的序列类__eq__()__hash__().