[Tutor] Unintentionally manipulating a list
Knacktus
knacktus at googlemail.com
Fri Feb 25 16:21:49 CET 2011
Am 25.02.2011 15:49, schrieb ranjan das:
>
> I am facing the following problem
>
>
> I have a list of the form
>
> INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.........] ]
>
>
> and I want an output of the form (selecting only those elements which
> have a Y associated with them)
>
> OUTPUT=[ ['A2-Y', 'B1-Y'],[....] ]
>
>
> I wrote the following code. Although it gives me the desired output, it
> CHANGES the list INPUT
>
> now after i run the code I get INPUT as the same as OUTPUT (which i dont
> want to happen). I have used the copy function but it still is not
> working. Any help or pointers is appreciated
>
> _CODE_
>
> from copy import copy
>
> temp=copy( INPUT )
> OUTPUT=temp
>
>
>
> for i in range(len(temp)):
>
> for j in range(len(temp[i])):
>
> for k in range(len(temp[i][j])):
>
> if temp[i][j][k][-1]=='Y':
>
> OUTPUT[i][j]=temp[i][j][k]
>
>
There's no need for an index. You can iterate over the elements directly
and create the result on the fly:
results = []
for sub_list in INPUT:
sub_results = []
for sub_sub_list in sub_list:
sub_sub_results = []
for entry in sub_sub_list:
if entry.endswith("Y"):
sub_sub_results.append(entry)
if sub_sub_results:
sub_results.append(sub_sub_results)
if sub_results:
results.append(sub_results)
Uuppsy daisy, not really readable code ;-). Your solution looks cleaner.
I bet, some of the gurus can come up with a real pythonic solution.
Cheers,
Jan
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list