P: 1

Hello. I need to sorting a list like z=[['111','C'],['234','A'],['12','Z'],['89','V'],['1110009','E'],['5','T']], by the length of the first element and then by his order.
Using z.sort() give [['111', 'C'], ['1110009', 'E'], ['12', 'Z'], ['234', 'A'], ['5', 'T'], ['89', 'V']]. I would to combinate the fuction 'len' but i don't know how to do it.
I try to find the soluce but I don't realy understand how use 'key' or lambda and even if it can help or if i need to make an other function...
I someone can help me... thanks
 
Share this Question
Expert Mod 2.5K+
P: 2,851

Here's an example of using lambda to sort on the length of the first element in a list of lists.  >>> z=[['111','C'],['234','A'],['12','Z'],['89','V'],['1110009','E'],['5','T']]

>>> sorted(z)

[['111', 'C'], ['1110009', 'E'], ['12', 'Z'], ['234', 'A'], ['5', 'T'], ['89', 'V']]

>>> z.sort(lambda a,b: cmp(len(a[0]), len(b[0])))

>>> z

[['5', 'T'], ['12', 'Z'], ['89', 'V'], ['111', 'C'], ['234', 'A'], ['1110009', 'E']]

>>> z.sort(lambda a,b: cmp(len(a[0]), len(b[0])), reverse=True)

>>> z

[['1110009', 'E'], ['111', 'C'], ['234', 'A'], ['12', 'Z'], ['89', 'V'], ['5', 'T']]

>>>
  Expert 100+
P: 613

If you still don't understand how it is done, there are many sorting tutorials on the web so you can write your own sort that will
1. extract each length in turn, i.e. extract all sublists where the first item has a length of 1, sort it and append to the output list. Do the same for a length of 2, and continue on until there are no more elements in the original list.
2. prepend the length, so it gets sorted first, and the rest of the list is then sorted in order as in the code below  z=[['234','A'],['111','C'],['12','Z'],['12','V'],

['1110009','E'],['5','T'],['20','B']]

z2 = [[len(x[0])] + x for x in z]


print z2, "\n"

z2.sort()

print z2
    Question stats  viewed: 1053
 replies: 2
 date asked: Apr 10 '14
