Reputation: 33
I have a List of Lists of Lists in python. I need to sort the highest level of lists based on one of the values in the lowest levels.
For a toy model, my list is created first with list small
, which is a list containing lists with three items each:
small = [["dog", 5, 6], ["cat", 391, 130], ["pig", 45, 2]...]`
Then there is a larger list, large
, that is created by appending the small list and another item together:
large.append([["category 1"], small])`
This is done in a loop, so if the loop has a counter of 5, it will proceed through a function that creates a list small
5 times, each time, appending it to list large
.
My goal is to sort the final list based on an element in the smallest list (the list that comprises the small
list). I am currently printing the large
list out line by line, with the small
list ordered by the index 1
of the lists within it (see: 5,10,15 in order, 1,3,6 in order, etc), so my output is this:
>category 1:
>['Dog', 5, 6]
>['Pig', 10, 2]
>['Cat', 15, 130]
>['Buffalo', 20, 1]
>['Newt', 25, 45]
>category 2:
>['Newt', 1, 1092]
>['Cat', 3, 352]
>['Pig', 6, 34]
>['Buffalo', 9, 12]
>['Dog', 12, 5]
>category 3:
>['Buffalo', 2, 12]
>['Pig', 4, 37]
>['Cat', 6, 34]
>['Newt', 8, 150]
>['Dog', 10, 52]
However, i would like to print the large
list in order of smallest to largest when looking at the element in index 1
in the list that makes up the smallest array. So my ideal output would be this:
>category 2:
>['Newt', 1, 1092]
>['Cat', 3, 352]
>['Pig', 6, 34]
>['Buffalo', 9, 12]
>['Dog', 12, 5]
>category 3:
>['Buffalo', 2, 12]
>['Pig', 4, 37]
>['Cat', 6, 34]
>['Newt', 8, 150]
>['Dog', 10, 52]
>category 1:
>['Dog', 5, 6]
>['Pig', 10, 2]
>['Cat', 15, 130]
>['Buffalo', 20, 1]
>['Newt', 25, 45]
I have tried sorting with itemgetter()
, however, when sorting large
with itemgetter()
, i can only sort the items in list large
, which are [category x]
and [[a,b,c], [a,b,c]]
. Is there a way to access the lowest level of elements for itemgetter? or another way to go about sorting this list?
Thanks.
Upvotes: 1
Views: 3666
Reputation: 8813
This can be done in one line:
sorted_large = sorted(large, key=lambda item: item[1][0][1])
The sorted
built-in function takes a key
parameter:
key
specifies a function of one argument that is used to extract a comparison key from each list element
Using a lambda
expression, the sorting key can be extracted.
Upvotes: 2