insert unique data in a list
Christian Tismer
tismer at stackless.com
Tue Dec 15 17:17:10 EST 2009
On 12/14/09 2:24 AM, knifenomad wrote:
> On 12월14일, 오전10시19분, knifenomad<knifeno... at gmail.com> wrote:
>
>> On 12월14일, 오전2시57분, mattia<ger... at gmail.com> wrote:
>>
>>
>>
>>
>>
>>
>>> Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto:
>>>
>>
>>>> How can I insert non-duplicate data in a list? I mean, is there a
>>>> particular option in the creation of a list that permit me not to use
>>>> something like:
>>>> def append_unique(l, val):
>>>> if val not in l:
>>>> l.append(val)
>>>>
>>
>>>> Thanks,
>>>> Mattia
>>>>
>>
>>> Ok, so you all suggest to use a set. Now the second question, more
>>> interesting. Why can't I insert a list into a set? I mean, I have a
>>> function that returns a list. I call this function several times and
>>> maybe the list returned is the same as another one already returned. I
>>> usually put all this lists into another list. How can I assure that my
>>> list contains only unique lists? Using set does'n work (i.e. the python
>>> interpreter tells me: TypeError: unhashable type: 'list')...
>>>
>> this makes the set type hashable.
>>
>> class Set(set):
>> __hash__ = lambda self: id(self)
>>
>> s = Set()
>> s.add(1)
>> s.add(2)
>> s.add(1)
>>
>> print s
>> set([1, 2])
>>
>> d = {}
>> d[s] = 'voila'
>>
>> print d
>> {Set([1,2]):'voila'}
>>
>> print d[s]
>> 'voila'- 원본 텍스트 숨기기 -
>>
>> - 원본 텍스트 보기 -
>>
>
> although it's not what you've asked about. it's intereting to make set
> hashable using __hash__.
Thoughtless messing with __hash__ is seldom useful.
>>> s1 = Set([1])
>>> s2 = Set([1])
>>> s1 == s2
True
>>> d = {}
>>> d[s1] = 3
>>> d[s2] = 5
>>> d
{Set([1]): 3, Set([1]): 5}
>>>
Equality is kept for comparison, but what is it worth to hash
them by id?
On the original problem:
You could turn you lists into tuples. This would be clean
and correct.
ciao - chris
--
Christian Tismer :^)<mailto:tismer at stackless.com>
tismerysoft GmbH : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/
More information about the Python-list
mailing list