[Python] Strano comportamento di list

Esalando Prassi alessandro.pisa a katamail.com
Lun 13 Ott 2008 19:55:56 CEST


2008/10/13 <michele a nectarine.it>

> Ciao,
> sto cercando di eliminare alcuni elementi da una lista, ma ottengo uno
> strano comportamento:
>
> >>> L
> [(1, 3, 16300), (2, 0, 12000), (3, 0, 13500), (3, 1500, 1000), (1, 4,
> 38473), (1
> , 5, 38473), (5, 5, 38473), (3, 5, 38473), (2, 5, 38473), (1, 1, 38473)]
> >>> for k in L:
> ...     if k[0] == 1:
> ...             L.remove(k)
> ...
> >>> L
> [(2, 0, 12000), (3, 0, 13500), (3, 1500, 1000), (1, 5, 38473), (5, 5,
> 38473), (3
> , 5, 38473), (2, 5, 38473)]
>
> Come vedete (1, 5, 38473) è rimasto, e non capisco perché.
>
> La mia versione di python:
> ActivePython 2.5.2.2 (ActiveState Software Inc.) based on
> Python 2.5.2 (r252:60911, Mar 27 2008, 17:57:18) [MSC v.1310 32 bit
> (Intel)] on
> win32
>
> Dove sbaglio?
> Grazie
>
>
> _______________________________________________
> Python mailing list
> Python a lists.python.it
> http://lists.python.it/mailman/listinfo/python
>
>

Come ti hanno detto l'errore e' modificare la lista durante il ciclo.
Probabilmente la soluzione migliore per risolvere il tuo problema e' usare
la list comprehension:
L = [x for x in L if not x[0]==1]

Ciao!
-- 
http://alepisa.blogspot.com
Esalando Prassi
-------------- parte successiva --------------
Un allegato HTML è stato rimosso...
URL: http://lists.python.it/pipermail/python/attachments/20081013/4cf08e29/attachment.htm 


Maggiori informazioni sulla lista Python