Newbie DATA STRUCTURES Question.
gbp
gpepice1 at nycap.rr.com
Sat Aug 5 00:21:53 EDT 2000
Thanks to everyone who replied. After using Python for a week I'm a lot
more comfortable with it.
After a couple days I figued out how to make a list of objects.
I got a little hung up on thinking in Perl terms. Once I stepped back
and let python be a different langauge stuff made more sense. In Perl
you can't really make a list of records you have to make a list of
pointers to records. In Python it seems you can make a list of anything
you want.
Huaiyu Zhu wrote:
>
> On Sat, 29 Jul 2000 02:57:03 GMT, gbp <gpepice1 at nycap.rr.com> wrote:
> >
> >I have experience with Perl but non with Python.
> >
> >I need to write a script to read a large text file into a structured
> >format.
> >
> >In Perl one can create a list of records using something like pointers.
> >So really you have a list of pointers-- each one pointing to an
> >anonymous record. Each record is some data from a line in the file.
> >
>
> Others have given more general answers, but I think you might have this
> specific question in mind: you have a file of form
>
> 11 12 13
> 21 22 23
> ...
>
> and you want to get a list of dictionaries (ie an array of hashes in Perl)
>
> result = [{'a':11, 'b':12, 'c':13},
> {'a':21, 'b':22, 'c':23},
> ...
> ]
>
> You can do it as the following (not tested)
>
> file = open(filename) # or file = sys.stdin
> names = ['a','b','c']
> result = []
> for line in file.readlines():
> fields = string.split(line) # or use re to extract the fields
> record = {}
> for name, field in map(None, names, fields):
> record[name] = field
> result.append(record)
>
> Hope this helps.
>
> Huaiyu
More information about the Python-list
mailing list