SystemTheory - 3 months ago 11
Python Question

# Python sort multiple lists by date and print list names

Working in Python I have four lists of dates, each in ascending order, where the lists are not of equal length. I want to print in ascending order with the list name as shown in desired output:

``````a = ['7-1-1987', '1-1-1990', ... ]
b = ['7-2-1987', '1-5-1990', ... ]
c = ['7-1-1987', '1-3-1990', ... ]
d = ['1-10-1985', '7-10-1986', ...]

[Desired Printout]
1-10-1985  d
7-10-1986  d
7-1-1987   a
7-1-1987   c
7-2-1987   b
1-1-1990   a
1-3-1990   c
1-5-1990   b
``````

This will give me visual confirmation of a sequence of events in four different sets of data. I would try to create a dictionary and sort by date for print to screen or disk but I have noticed similar answers using map or lambda functions that may provide a more elegant solution. If I am storing this information on disk what is the best data structure and solution?

``````#  Create the list of all dates, combining the four lists you have. Keep
#  the information about which list value comes from
all_dates = [(x, 'a') for x in a] + [(x, 'b') for x in b] + [(x, 'c') for x in c] + [(x, 'd') for x in d]

#  Sort with key a simple date parser. The way it works is:
#     1. It takes a date 11-12-2012 and splits it by '-' so that we get ['11', '12', '2012']
#     2. Reverses the list ([::-1]) so that the year is the most significant (['2012', '12', '11'])
#     3. Applies int to each so that they are compared as numbers ([2012, 12, 11]). Note that Python can automatically compare things like that
all_dates.sort(key = lambda x: list(map(int, x[0].split('-')[::-1])))

#  Print the result
for date in all_dates:
print ' '.join(date)
``````