set using alternative hash function?
gagsl-py2 at yahoo.com.ar
Thu Oct 15 17:15:42 CEST 2009
En Thu, 15 Oct 2009 11:42:20 -0300, Austin Bingham
<austin.bingham at gmail.com> escribió:
> On Thu, Oct 15, 2009 at 4:06 PM, Anthony Tolle <anthony.tolle at gmail.com>
>> Why not use a dict? The key would be the object name. Pretty much
>> the same behavior as a set (via the key), and you can still easily
>> iterate over the objects.
> To reiterate, dict only gets me part of what I want. Whereas a set
> with uniqueness defined over 'obj.name' would guarantee no name
> collisions, dict only sorta helps me keep things straight; it doesn't
> actually enforce that my values have unique names.
I think you didn't understand correctly Anthony Tolle's suggestion:
py> class Foo:
... def __init__(self, name): self.name = name
py> objs = [Foo('Joe'), Foo('Jim'), Foo('Tom'), Foo('Jim')]
[<__main__.Foo instance at 0x00BB8238>,
<__main__.Foo instance at 0x00BB83C8>,
<__main__.Foo instance at 0x00BB7B20>,
<__main__.Foo instance at 0x00BB7DC8>]
py> d = dict((o.name, o) for o in objs)
['Jim', 'Joe', 'Tom']
[<__main__.Foo instance at 0x00BB7DC8>,
<__main__.Foo instance at 0x00BB8238>,
<__main__.Foo instance at 0x00BB7B20>]
keys in a dict are unique; values form the set you're looking for. If it's
more complex that just a name, define a function:
d = dict((my_funny_key_extractor(o), o) for o in objs)
If you feel so inclined, you could implement the MutableSet ABC based on
this and have a full featured set implementation.
More information about the Python-list