By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,351 Members | 1,275 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,351 IT Pros & Developers. It's quick & easy.

sorting a list complex by length of the first element

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
Apr 10 '14 #1
Share this Question
Share on Google+
2 Replies

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.
Expand|Select|Wrap|Line Numbers
  1. >>> z=[['111','C'],['234','A'],['12','Z'],['89','V'],['1110009','E'],['5','T']]
  2. >>> sorted(z)
  3. [['111', 'C'], ['1110009', 'E'], ['12', 'Z'], ['234', 'A'], ['5', 'T'], ['89', 'V']]
  4. >>> z.sort(lambda a,b: cmp(len(a[0]), len(b[0])))
  5. >>> z
  6. [['5', 'T'], ['12', 'Z'], ['89', 'V'], ['111', 'C'], ['234', 'A'], ['1110009', 'E']]
  7. >>> z.sort(lambda a,b: cmp(len(a[0]), len(b[0])), reverse=True)
  8. >>> z
  9. [['1110009', 'E'], ['111', 'C'], ['234', 'A'], ['12', 'Z'], ['89', 'V'], ['5', 'T']]
  10. >>> 
Apr 10 '14 #2

Expert 100+
P: 626
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 sub-lists 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. pre-pend the length, so it gets sorted first, and the rest of the list is then sorted in order as in the code below
Expand|Select|Wrap|Line Numbers
  1. z=[['234','A'],['111','C'],['12','Z'],['12','V'],
  2.    ['1110009','E'],['5','T'],['20','B']]
  3. z2 = [[len(x[0])] + x for x in z]
  5. print z2, "\n"
  6. z2.sort()
  7. print z2 
Apr 10 '14 #3

Post your reply

Sign in to post your reply or Sign up for a free account.