Get item from set
Aahz
aahz at pythoncraft.com
Mon Apr 27 12:10:52 EDT 2009
In article <gt1kb7$jqg$03$1 at news.t-online.com>,
Peter Otten <__peter__ at web.de> wrote:
>
>Here's a trick to find the actual element. I think Raymond Hettinger posted
>an implementation of this idea recently, but I can't find it at the moment.
Your code is inverted from Raymond's:
http://code.activestate.com/recipes/499299/
class _CaptureEq:
'Object wrapper that remembers "other" for successful equality tests.'
def __init__(self, obj):
self.obj = obj
self.match = None
def __eq__(self, other):
result = (self.obj == other)
if result:
self.match = other
return result
# support hash() or anything else needed by __ contains__
def __getattr__(self, name):
return getattr(self.obj, name)
def get_equivalent(container, item, default=None):
'''Gets the specific container element matched by: "item in container".
Useful for retreiving a canonical value equivalent to "item". For
example, a caching or interning application may require fetching a
single representativ e instance from many possible equivalent
instances).
>>> get_equivalent(set([1, 2, 3]), 2.0) # 2.0 is equivalent to 2
2
>>> get_equivalent([1, 2, 3], 4, default=0)
0
'''
t = _CaptureEq(item)
if t in container:
return t.match
return default
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur." --Red Adair
More information about the Python-list
mailing list