473,549 Members | 2,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting a list complex by length of the first element

1 New Member
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
2 1334
bvdet
2,851 Recognized Expert Moderator Specialist
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
dwblas
626 Recognized Expert Contributor
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]
  4.  
  5. print z2, "\n"
  6. z2.sort()
  7. print z2 
Apr 10 '14 #3

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

Similar topics

8
2360
by: ehames | last post by:
Hi guys, As far as I know, for any type T, and positive integer N, if I have an array declared as: T array; then, &array and array are the same element. Is there any reason why a
2
1821
by: Ben Bush | last post by:
I have a lis: ,,,,,] I want a code to test when the difference between the first element in the list of list is equal to or larger than 6, then move the previous lists to the end of the list. that is: ,,,,,]
10
14684
by: garyusenet | last post by:
Hi I'm using the following to reference each 'element' (is this the correct term) in an arraylist: - foreach (InternetExplorer ie in ar) { ... } Q. How do I reference the nth element in an array list? Specifically in this example I want to reference the first element of the arraylist ar.
3
1425
by: Arkady Frenkel | last post by:
Hi, guys! Is it possible to write byte array, I receive already from one stream to another, but not from first element, without copy part of array to new one. I mean I have byte array and need to do stream.Write( array from element i,0, array.Length - i )? TIA Arkady
1
2866
by: Giovanni Toffoli | last post by:
Hi, I'm not in the mailing list. By Googling, I stepped into this an old post: (Thu Feb 14 20:40:08 CET 2002) of Jeff Shannon: http://mail.python.org/pipermail/python-list/2002-February/128438.html <<< def SortOnItem(mylist, index): templist = , line) for line in mylist ]
3
6001
by: jm.suresh | last post by:
Hi, I have a list and I want to find the first element that meets a condition. I do not want to use 'filter', because I want to come out of the iteration as soon as the first element is found. I have implemented it this way, may be, there should be a built in hiding somewhere in the standard libraries? def exists(iterable, condition): '''...
10
6269
by: Chris Forone | last post by:
Hello Group, there is some memberfunc for std::valarray to return a pointer to the first element in the array. How do i use this? Thanx a lot. HAND Chris
4
4553
by: mab464 | last post by:
I have this code on my WAMP server running on my XP machine if ( isset( $_POST ) ) { for($i=0; $i<count($_POST);$i++) { if ($ans != NULL ) $ans .= ", " . $_POST ; // Not the first element so append a comma
2
14393
by: DD2783 | last post by:
I'm currently trying to remove the first element in an int array using objects in C#. I have just coded how to add an element to that start of the array and though it was just a case of changing a few things. Here's the code for the addFirst() but i can't for the life of me figure out removeFirst() public void addFirst(int value) ...
0
7518
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7715
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7808
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5087
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1935
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.