I have an outermost list which contains a monthly total count of different items in this format. Every month has the same items.
big_list = [
[
(20, 'Item A', 'Jan'),
(30, 'Item B', 'Jan'),
(12, 'Item C', 'Jan'),
],
[
(22, 'Item A', 'Feb'),
(34, 'Item B', 'Feb'),
(15, 'Item C', 'Feb'),
],
.... # until 'Dec'
]
And I want to sort this list based on the total number of item counts throughout a year. (The sum of the first field in the tuple of a particular item throughout the year). For instance, if Item C has the most counts in the two months followed by Item A and Item B, the end result would be
[
[
(12, 'Item C', 'Jan'),
(20, 'Item A', 'Jan'),
(30, 'Item B', 'Jan'),
],
[
(15, 'Item C', 'Feb'),
(22, 'Item A', 'Feb'),
(34, 'Item B', 'Feb'),
],
... # until 'Dec'
]
# Item C = 12 + 15 = 27
# Item A = 20 + 22 = 42
# Item B = 30 + 34 = 64
How can I achieve this? Any help or enlightenment would be much appreciated.
gives us
s– the sums we want to use to sort:{'Item A': 42, 'Item B': 64, 'Item C': 27}And finally:
changes
big_listto:This solution works for lists within months in any order and also if some item does not appear in some month.