Brian van den Broek wrote: > Morten Juhl Johansen said unto the world upon 16/09/06 08:29 AM: >> # Newbie warning >> I am making a timeline program. It is fairly simple. >> I base it on appending lists to a list. >> Ex. >> [[year1, "headline1", "event text1"], [year2, "headline2", "event text2"]] >> >> This seemed like a brilliant idea when I did it. It is easy to sort. >> Now, if I want to OUTPUT it, how do I indicate that I want to extract >> first entry in a list in a list? How do I print the separate entries? >> >> Yours, >> Morten >> > > Hi Morten, > > Andrei answered the question you asked; I'd like to make a suggestion > involving a bit of reworking. > > You might think about structuring your timeline data as a dictionary, > rather than a list. So: > > >>> timeline_data = { > ... 800: ["Charlemagne Crowned Holy Roman Emperor", 'event_text'], > ... 1066: ["Battle at Hastings", 'event_text']} > > > This makes it very easy to access a given year's data: > > >>> timeline_data[800] > ['Charlemagne Crowned Holy Roman Emperor', 'event_text'] > > and > > >>> timeline_data[800][0] > 'Charlemagne Crowned Holy Roman Emperor' > > will get you the headline alone. > > You expressed a liking for the lists as they are easy to sort. On > recent versions of python one can easily obtain a sorted list of > dictionary keys, too: > > >>> d = {1:2, 3:4, 43545:32, -3434:42} > >>> d > {1: 2, 3: 4, -3434: 42, 43545: 32} > >>> sorted(d) > [-3434, 1, 3, 43545] > >>> > > (Older versions of Python can do the same, but with a bit more > keyboard action.) > > So, if you wanted to print the headlines in increasing year order: > > >>> for year in sorted(timeline_data): > ... print timeline_data[year][0] > ... > Charlemagne Crowned Holy Roman Emperor > Battle at Hastings > >>> > > > You say you are new to Python. Well, it might not now be obvious why > dictionaries are especially useful, but they are *central* to the > pythonic approach. The sooner you become comfortable with them, the > better (IMHO).
I agree that dicts are extremely useful, but I don't think they add anything in this case unless there is actually a need for keyed access. A list of lists (or tuples) seems very appropriate to me. A good alternative might be a list of Bunches. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor