On 07/11/2013 08:18 AM, Sivaram Neelakantan wrote:

Thanks for the detailed explanation below.  I've replied below.

On Thu, Jul 11 2013,Dave Angel wrote:


third choice?  Put them in a list.  Whaddya know, they already are.
So just assign a name to that list.  Referencing them is now by
subscript. And you can actually do slices and loops readily, which you
can't easily do on "var names."

This seems the easiest but I already foresee hardcoded subscripts all
over the code which I will promptly forget the very next day of what
it stands for.


Good. Then you're changing the requirements spec from unreasonable to something attainable. You're the one who had all these numeric variables on the left hand side of the assignment. If you want them to be real names, then you're going to make progress.

Next question is where do these names come from? In the text file, there seem to be just a bunch of values, separated by whitespace. So the only characteristic they have at that moment is sequence. You can refer to the 19th item in the text file, or the 4th.

One example of a name correlation would be the traditional comma-separated file (csv). The first line lists the names, separated by commas, and subsequent line(s) contain values for those names. it's one way of import/export from a spreadsheet, database, etc.

So if you can put the names in the text file, then you can easily make a dict (see below), or a namespace with those names (see below).


Next choice?  Put them in a dict.  This works just like a list, except
the subscript doesn't have to be continguous ints.

alright.


Final choice?  Put them in a namespace.  Something like:

class NewSpace:
     pass

data = NewSpace()
for index, item in enumerate(lines.split()):
     data.__dict__["x" + str(index)] = item


OO, I'd stay away till I get the basics right.


Chris Warrick corrected me on this. I knew about setattr(), but forgot it could be used in this way.

So if you now have a list of names (each a str, and one that's a legal name in Python), you could do:

data = NewSpace()
for name, item in zip(names, lines.split()):
    setattr(data, name, item)

And now you can have say print(data.address1) to print out the address1 string from that file.

Try it with some simple data, it's not very hard.


--
DaveA

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to