我正在尝试set().issubset()
用于比较序列。正如您可以想象的那样,它没有按预期工作;)提前:对于长代码块感到抱歉。
class T(object):
def __init__(self, value, attributes = None):
self.value = value
self.attributes = Attributes(attributes)
def __eq__(self, other):
if not isinstance(other, T):
return False
if self.value == other.value and self.attributes == other.attributes:
return True
else:
return False
def __ne__(self, other):
if not isinstance(other, T):
return True
if self.value != other.value or self.attributes != other.attributes:
return True
else:
return False
class Attributes(dict):
def __init__(self, attributes):
super(dict, self)
self.update(attributes or dict())
def __eq__(self, other):
if self.items() == other.items():
return True
else:
return False
def __ne__(self, other):
if not self.items() == other.items():
return True
else:
return False
def __cmp__(self, other):
return self.items().__cmp__(other.items())
x = [T("I", {'pos': 0}), T("am", {'pos': 1}), T("a", {'pos': 2}), T("test", {'pos': 3})]
y = [T("a", {'pos': 2}), T("test", {'pos': 3})]
xx = set(x)
yy = set(y)
assert y[0] == x[2], "__eq__ did fail, really?" #works
assert y[1] == x[3], "__eq__ did fail, really?" #works
assert xx-(yy-xx) == xx, "set subtract not working" #works, but is nonsense. see accepted answer
assert not xx.issubset(yy), "i am doing it wrong..." #works
assert yy.issubset(xx), "issubset not working :(" #FAILS!
运行上面的代码使最后一个断言失败:
$ python
Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import issubsettest
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "issubsettest.py", line 52, in <module>
assert yy.issubset(xx), "issubset not working :("
AssertionError: issubset not working :(
>>>
我在这里想念什么?