[Tutor] looping problem
Kent Johnson
kent37 at tds.net
Sun Sep 24 04:49:14 CEST 2006
John Fouhy wrote:
> 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.
That's a good point, though the OP didn't seem to have a problem with
memory.
>
> 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 :-) )
Since the end goal seems to be to create a dictionary, there is really
no need to create the intermediate lists at all. You could do something
like this (following your file example):
d = {}
while 1:
try:
key, _, value = f2.next(), f2.next(), f2.next()
d[key] = value
except StopIteration:
pass
To do this with a list instead of a file use f2=iter(reallyBigList).
Kent
More information about the Tutor
mailing list