मैं दृश्यों की तुलना के लिए set().issubset()
उपयोग करने के लिए कोशिश कर रहा हूँ। जैसा कि आप कल्पना कर सकते हैं, यह अपेक्षित काम नहीं कर रहा है;) अग्रिम में: लंबे कोड-ब्लॉब के लिए खेद है।अजगर सेट()। Issubset() काम नहीं कर के रूप में की उम्मीद
$ 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 :(
>>>
मैं यहाँ क्या याद आ रही है: कोड ऊपर
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!
चल रहा है पिछले दावे विफल रहता है?
मुझे लगता है कि ऐसा इसलिए है क्योंकि उपयोगकर्ता –
मुझे लगता है कि समस्या यह है कि आपकी कक्षा 'टी' विधि' __hash__' को ओवरराइड नहीं करती है। [दस्तावेज़ीकरण] देखें (http://docs.python.org/reference/datamodel.html#object.__hash__): * यदि यह __cmp __() या __eq __() को परिभाषित करता है लेकिन __hash __() नहीं है, तो इसके उदाहरण उपयोग योग्य नहीं होंगे हैश संग्रह में।* – halex
मैंने अभी आपके कोड को पायथन 3.3 के साथ परीक्षण किया है, जो त्रुटि देता है: 'TypeError: unhashable type:' t'' पंक्ति 'xx = set (x)' पर यह निश्चित रूप से '__hash__' की कमी है। – halex