2012-04-11 1 views
1

파이썬 튜플에서 차이점을 설정해야하지만 차이점은 내 튜플의 첫 번째 요소를 고려해야합니다. cmp 함수 나 키 함수를 파이썬의 차이점 집합 (또는 다른 집합 연산)에 전달 2.7

내가 라이브러리가 차이

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 
를 확인하기 위해 itertools.ifilterfalse 기능을 사용하는 발견 sets.py 모듈에 파고이 클래스 접근

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  

를 사용하여 (uncessfully) 내가 한이를 달성하기 위해

그러나 나는 이것으로 유용한 것을 할 수 없었습니다.

답변

5

이 작업을 수행하는 유일한 방법은 __eq__()__hash__()의 첫 번째 요소 만 사용하는 자체 시퀀스 클래스를 정의하는 것입니다.

+0

굉장! 고맙습니다. –

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)) 
관련 문제