1

我需要在 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     

在 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

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

4

2 回答 2

5

唯一的方法是定义你自己的序列类,它只使用__eq__()and中的第一个元素__hash__()

于 2012-04-11T01:35:08.593 回答
0

有点晚了,但这里有一个替代方案。它将保留 Set 和 dict 的所有方法。尝试这个:

from sets import Set
from itertools import ifilterfalse

class MyDict(dict):
    custom_list = None
    def contains(self, a):
        if not self.custom_list:
            self.custom_list = [key[0] for key in self]
        return a[0] in self.custom_list

    def update_by_dict(self, _dict):
        for key in _dict:
            self[key] = _dict[key]


class MySet(Set):
    def diff_by_first_item(self, other):
        result = self.__class__()
        data = result._data
        try:
            otherdata = other._data
        except AttributeError:
            otherdata = Set(other)._data
        yetanother = MyDict()
        yetanother.update_by_dict(otherdata)
        value = True
        for elt in ifilterfalse(yetanother.contains, self):
            data[elt] = value
        return result

if __name__ == "__main__":
    a = [(0, 'a'), (1, 'b'), (2, 'c')]
    b = [(1, 'c')]
    print MySet(a).diff_by_first_item(b)
    print MySet(a).diff_by_first_item(MySet(b))
    print MySet(a).diff_by_first_item(set(b))
于 2012-04-11T03:12:08.850 回答