[Tutor] looping problem
John Fouhy
john at fouhy.net
Sun Sep 24 04:02:27 CEST 2006
On 24/09/06, Python <python at venix.com> wrote:
> slices may be the best way to go
> listA = biglist[0::3] # start from index 0 taking every third element
> listB = biglist[2::3] # start from index 2 taking every third element
I'm not certain they would be.. If you do that, you will:
1. Create a really big list.
2. Go through the list, taking every third element.
3. Go through the list again, taking every third+2 element.
If the list is really big, step 1. might take some time and/or space,
and you would like to avoid it.
If we have:
f2= open('myfile','r')
listA = []
listB = []
then we can iterate through f2 as follows:
for i, line in enumerate(f2):
if i % 3 == 0 then
listA.append(line)
elif i % 3 == 2 then
listB.append(line)
This may be faster..
(although I should like to see evidence before committing to that
statement :-) )
--
John.
More information about the Tutor
mailing list