[Tutor] Aschenputtel problem
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Fri Sep 16 11:30:07 CEST 2005
Well, in the specific case of numeric arrays, you can use Numeric or
numarray :
from Numeric import array, compress
ol = array(original_list)
selection = array([condition(i) for i in original_list)
list1 = compress(selection, ol)
list2 = compress(!selection, ol)
Even better, if condition can be expressed directly on the matrix itself
(which is pretty common with Numeric/numarray):
ol = array(original_list)
selection = condition(ol)
list1 = compress(selection, ol)
list2 = compress(!selection, ol)
Remember: if you have complex index operations on arrays of numbers,
Numeric (and even more numarray) contains a lot of very usefull
efficient functions.
Pierre
Christopher Arndt a écrit :
> Hi,
>
> I wonder if there is a shorter form of the following idiom:
>
> list1 = []
> list2 = []
> for item in original_list:
> if condition(item):
> list1.append(item)
> else:
> list2.append(item)
>
> (optional step:)
>
> original_list[:] = list1
>
>
> I call this the "Aschenputtel" problem, because it is described by the famous
> quote from the fairy tale as told by the Grimm brothers:
>
> "Die guten ins Töpfchen, die schlechten ins Kröpfchen."
>
> (The good ones in the pot, the bad ones in the crop)
>
> Chris
>
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Pierre Barbier de Reuille
INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France
tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68
More information about the Tutor
mailing list