Main Content

Exception, Lambda, Generator, Slice, Dict - examples in one Python program

Archive - Originally posted on "The Horse's Mouth" - 2013-03-04 18:10:13 - Graham Ellis

A new example from last week's Python course, showing exception, lambda, generator and list slices in a practical programming example. The task we took was to go through a file of railway stations and ticket sales figures, and report on the most and least used 20 in the UK. The programs's [here].

a) The open statement - when used within a for loop structure returns a generator object in modern versions of Python, and that means that we can loop through the data without reading it ahead into a list as simply as
  for record in open("railstats.xyz"):

b) Most data rows within the file contain numbers in the last field of each line, but a few of them (stations that were not open during the last year of data collection) contain the word NULL. I've caught exceptions to trap these lines, simply passing the error over as these are special cases outside the scope of my application

c) I need to sort the dict that I've built ... but a dict can't be sorted. So I've extracted a list of keys and sorted that list. The sorting's going to be based on the contents of the original dict, so I need to provide a sort routine that I've done in the form of a lambda - that's rather like a oneline function with no name. Quicker to code, easy to read inline:
  places = usage.keys()
  places.sort(lambda x,y: usage[x] - usage[y])

d) I've picked our the first 20, and the last 20, records after sorting using list slices. Note the subtle syntax difference at the start and end of the list.
  for place in places[:20]:
  for place in places[-20:]:

There are lots of examples on our web site and in our course notes showing each of these features ... but the exmaple that I've referred to here shows interaction between them.