Assigning to lists with arbitrary names

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Thu Oct 11 22:40:16 EDT 2001


On Tue, 09 Oct 2001 14:34:09 -0500, Stephen Boulet
<stephen.boulet at motorola.com> wrote:
>I can't quite figure out how to do this.
>
>I have 100 text files in a directory: file00.txt to file99.txt.
>
>I want to read each file in turn, parse it, and generate a list from
>each file.
>
>Here's the problem: I want to name each list list00 to list99. I don't
>want to do list[0] to list[99] (since each list is actually a list of
>lists, and I'd like to avoid a list of lists of lists  :).
>
>Any idea how I can do this? Thanks.

You want the list of lists.  Unless your parser generates a list of lists, you
will not get a list of lists of lists.

def process_file(fp):
    # read from fp and generate a list

parsed_files = [ process_file(open('file%02d.txt' % n)) for n in range(100) ]



If your parser does generate a list of lists, and you think a lot of deeply
nested lists may be unclear for whatever reason, you should probably define a
more appropriate type for a parsed file.  E.g.:

class Parsed_file:
    def __init__(self, fp):
        # read data from fp and store in whatever format
    # ... define various methods to do what you need with the data

Now you have a list of Parsed_files which is pretty clear.


Perlis says "The string is a stark data structure..." and the list is similar.
It's very convenient and flexible in its generality, but don't be afraid to
define your own type.  When you move away from lists you lose access to all
the list manipulation functions (like when you move away from text files you
lose the use of grep, etc.).  When you move away from classes you can lose the
clarity and ease of use of a specially defined type.

Whether to use one or the other depends on the circumstance and taste.  



More information about the Python-list mailing list