c2=[]
row1=[1,22,53]
row2=[14,25,46]
row3=[7,8,9]
c2.append(row2)
c2.append(row1)
c2.append(row3)
c2 is now:
[[14, 25, 46], [1, 22, 53], [7, 8, 9]]
how do i sort c2 in such a way that for example:
for row in c2:
sort on row[2]
the result would be:
[[7,8,9],[14,25,46],[1,22,53]]
The
keyargument tosortspecifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simplelambdathat returns the last element from each row to be used in the sort:A
lambdais a simple anonymous function. It’s handy when you want to create a simple single use function like this. The equivalent code not using alambdawould be:If you want to sort on more entries, just make the
keyfunction return a tuple containing the values you wish to sort on in order of importance. For example:or: