Sorting a list of tuples arranges them in order of the first element in each tuple first. If two or more tuples have the same first element, they are ordered by the second element, and so on:
>>> sorted([(3,1), (1,4), (3,0), (2, 2), (1, -1)])
[(1, -1), (1, 4), (2, 2), (3, 0), (3, 1)]
This suggests a way of using zip
to sort one list using the elements of another. Implement this method on the data below to produce an ordered list of the average amount of sunshine in hours in London by month. Output the sunniest month first.
Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec |
44.7 | 65.4 | 101.7 | 148.3 | 170.9 | 171.4 | 176.7 | 186.1 | 133.9 | 105.4 | 59.6 | 45.8 |
Simply zip the lists of sunshine hours and month names together and reverse-sort the resulting list of tuples:
>>> months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
... 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
>>> sun = [44.7, 65.4, 101.7, 148.3, 170.9, 171.4,
... 176.7, 186.1, 133.9, 105.4, 59.6, 45.8]
>>> for s, m in sorted(zip(sun, months), reverse=True):
... print('{}: {:5.1f} hrs'.format(m, s))
...
Aug: 186.1 hrs
Jul: 176.7 hrs
Jun: 171.4 hrs
May: 170.9 hrs
Apr: 148.3 hrs
Sep: 133.9 hrs
Oct: 105.4 hrs
Mar: 101.7 hrs
Feb: 65.4 hrs
Nov: 59.6 hrs
Dec: 45.8 hrs
Jan: 44.7 hrs