performance question: dictionary or list, float or string?

bkamrani at gmail.com bkamrani at gmail.com
Thu Dec 4 05:12:44 EST 2008


About the piece of code you posted, there is something I don't
understand.

        for i, line in data:

where data is a file object. Is it legal to write that?
I believe it results in "too many values to unpack" or do I miss
something?

/Ben

On Dec 4, 10:26 am, bkamr... at gmail.com wrote:
> Matt, really thanks for your comments!
> Even thogh it was not a direct answer to my questions,
> I like your coding style very much and I think you have a good point.
>
> About the number of line in the file, because I get that info from
> another
> in advance. Therefore I thought it could be hard coded.
>
> BTW, could you recommend a book or a note on points you have mentioned
> so that I can learn more like that?
>
> Thanks,
> /Ben
>
> > # this is just bad style in python:
> > line = fil.next(); spl = line.split()
> > # better written
> > spl = fil.next().split()
>
> > I would just do it this way:
>
> > def read_as_list(data, regions=25, maxlines=20000):
> >     # If data is a filename, open the file. If it is a file
> >     # object or any sequence of 'lines' it should just work.
>
> >     file_opened = False
> >     if isinstance(data, basestring):
> >         data = open(data, 'r')
> >         file_opened = True
>
> >     forces = [[] for _ in xrange(regions)]
> >     try:
> >         for i, line in data:
> >             if i == maxlines:
> >                 break
> >             forces[i % 25].append(line.split())
> >     finally:
> >         if file_opened:
> >             f.close()
> >     return forces
>
> > Matt
>
>




More information about the Python-list mailing list