首先是最简单的方法。那是通过使用像 cmets 建议的元组:
# your sets
a = {(2, 2), (2, 10), (3, 6), (4, 5)}
b = {(3, 6), (6, 6), (9, 1), (9, 8)}
c = {(2, 2), (6, 7), (7, 5), (9, 2)}
d = {(1, 2), (2, 2), (3, 6), (7, 5)}
#print output
print("Compare a to c+d:",a&(c|d))
print("Compare b to c+d:",b&(c|d))
print("Compare c to a+b:",c&(a|b))
print("Compare d to a+b:",d&(a|b))
输出:
Compare a to c+d: {(3, 6), (2, 2)}
Compare b to c+d: {(3, 6)}
Compare c to a+b: {(2, 2)}
Compare d to a+b: {(3, 6), (2, 2)}
如果您的输入与您的示例中描述的一样,我会这样做:
class Coord:
def __init__(self, x, y):
self.x = x
self.y = y
@staticmethod
def from_string(coord_str):
x,y = coord_str.strip("[]").split(",")
return Coord(int(x),int(y))
@staticmethod
def convert(my_iter):
return set(map(Coord.from_string, my_iter))
def __eq__(self, other):
if not isinstance(other, Coord):
return False
return self.x == other.x and self.y == other.y
def __repr__(self):
return "Coord(%s, %s)" % (self.x, self.y)
def __hash__(self):
return hash(self.__repr__())
# your sets
a = {'[2, 2]', '[2, 10]', '[3, 6]', '[4, 5]'}
b = {'[3, 6]', '[6, 6]', '[9, 1]', '[9, 8]'}
c = {'[2, 2]', '[6, 7]', '[7, 5]', '[9, 2]'}
d = {'[1, 2]', '[2, 2]', '[3, 6]', '[7, 5]'}
# creating sets
set_a = Coord.convert(a)
set_b = Coord.convert(b)
set_c = Coord.convert(c)
set_d = Coord.convert(d)
set_a_and_b = Coord.convert(a)|Coord.convert(b)
set_c_and_d = Coord.convert(c)|Coord.convert(d)
# print requested information
print("Compare a to c+d:",set_a.intersection(set_c_and_d))
print("Compare b to c+d:",set_b.intersection(set_c_and_d))
print("Compare c to a+b:",set_c.intersection(set_a_and_b))
print("Compare d to a+b:",set_d.intersection(set_a_and_b))
输出:
Compare a to c+d {Coord(2, 2), Coord(3, 6)}
Compare b to c+d {Coord(3, 6)}
Compare c to a+b {Coord(2, 2)}
Compare d to a+b {Coord(2, 2), Coord(3, 6)}