python集合运算

class orderset:
    def __init__(self,list=[]):
        self.data = [x for x in list]
    def __repr__(self):
        return "orderset(%r)" % self.data
    def __and__(self,rhs): #与运算 取交集&
        lst = []
        i = [x for x in self.data if x in rhs.data]
        lst.extend(i)
        return lst 
    def __or__(self,rhs):#或运算 取并集|
        lst = []
        lst.extend(self.data)
        i = [x for x in rhs.data if x not in self.data]
        lst.extend(i)
        return lst
    def __xor__(self,rhs): #异或 取对称补集^
        lst = []
        # i = [x for x in self.data if x not in rhs.data]
        # lst.extend(i)
        for x in rhs.data:
            if x not in self.data:
                lst.append(x)
        for y in self.data:
            if y not in rhs.data:
               lst.append(y)
        return lst
    def __eq__(self,rhs):
        if self.data == rhs.data:
            return True
        return False
    def __contains__(self,e):
        if e in self.data:
            return True
        return False
s1 = orderset([1,2,3,4])
s2 = orderset([3,4,5])
print(s1)
print(s2)
print(s1 & s2)
print(s1 | s2)
print(s1 ^ s2)
if orderset([1,2,3]) != orderset([1,2,3,4]):
    print("orderset([1,2,3])","不相等","orderset([1,2,3,4])")
if s2 == orderset([3,4,5]):
    print(s2,"等于","orderset([3,4,5])")
if 2 in s1:
    print("2","在s1内")

你可能感兴趣的:(python集合运算)