473,657 Members | 2,765 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sort the list

I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list
based on the second value in the item?
That is,
I want the list to be:
[[3,2],[1,4],[2,5],[3,9]]
Nov 22 '05 #1
11 1672
Shi Mu wrote:
I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list
based on the second value in the item?
That is,
I want the list to be:
[[3,2],[1,4],[2,5],[3,9]]


lst = [[1,4],[3,9],[2,5],[3,2]]
lst [[1, 4], [3, 9], [2, 5], [3, 2]]

lst.sort(cmp = lambda x,y: cmp(x[1], y[1]))
lst [[3, 2], [1, 4], [2, 5], [3, 9]]


works for Python 2.4
in earlier Pythons just let cmp = .. away

Regards, Daniel

Nov 22 '05 #2
Shi Mu wrote:
I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list
based on the second value in the item?
That is,
I want the list to be:
[[3,2],[1,4],[2,5],[3,9]]


lst = [[1,4],[3,9],[2,5],[3,2]]
lst [[1, 4], [3, 9], [2, 5], [3, 2]]

lst.sort(cmp = lambda x,y: cmp(x[1], y[1]))
lst [[3, 2], [1, 4], [2, 5], [3, 9]]


works for Python 2.4
in earlier Pythons just let cmp = .. away

Regards, Daniel

Nov 22 '05 #3
On 11/21/05, Daniel Schüle <uv**@rz.uni-karlsruhe.de> wrote:
Shi Mu wrote:
I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list
based on the second value in the item?
That is,
I want the list to be:
[[3,2],[1,4],[2,5],[3,9]]


>>> lst = [[1,4],[3,9],[2,5],[3,2]]
>>> lst [[1, 4], [3, 9], [2, 5], [3, 2]] >>>
>>>
>>> lst.sort(cmp = lambda x,y: cmp(x[1], y[1]))
>>> lst [[3, 2], [1, 4], [2, 5], [3, 9]] >>>


works for Python 2.4
in earlier Pythons just let cmp = .. away

Regards, Daniel

what does let cmp = .. away mean?
Nov 22 '05 #4
On 11/21/05, Daniel Schüle <uv**@rz.uni-karlsruhe.de> wrote:
Shi Mu wrote:
I have a list like [[1,4],[3,9],[2,5],[3,2]]. How can I sort the list
based on the second value in the item?
That is,
I want the list to be:
[[3,2],[1,4],[2,5],[3,9]]


>>> lst = [[1,4],[3,9],[2,5],[3,2]]
>>> lst [[1, 4], [3, 9], [2, 5], [3, 2]] >>>
>>>
>>> lst.sort(cmp = lambda x,y: cmp(x[1], y[1]))
>>> lst [[3, 2], [1, 4], [2, 5], [3, 9]] >>>


works for Python 2.4
in earlier Pythons just let cmp = .. away

Regards, Daniel

what does let cmp = .. away mean?
Nov 22 '05 #5
Daniel Schüle <uv**@rz.uni-karlsruhe.de> wrote:
lst.sort(lambda x,y: cmp(x[1], y[1]))


Since no-one mentioned it and its a favourite of mine, you can use the
decorate-sort-undecorate method, or "Schwartzia n Transform"

eg

lst = [[1,4],[3,9],[2,5],[3,2]]
# decorate - ie make a copy of each item with the key(s) first and the
# actual object last
L = [ (x[1],x) for x in lst ]
# sort
L.sort()
# undecorate
L = [ x[-1] for x in L ]

The Schwartzian transform is especially good when making the key is
expensive - it only needs to be done N times, wheras a typical sort
routine will call the cmp function N log N times. Its expensive in
terms of memory though.

With python 2.4 you can wrap it up into one line if you want

[ x[-1] for x in sorted([ (x[1],x) for x in lst ]) ]

or even

[ x[-1] for x in sorted((x[1],x) for x in lst) ]

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Nov 22 '05 #6
Nick Craig-Wood:
Since no-one mentioned it and its a favourite of mine, you can use the
decorate-sort-undecorate method, or "Schwartzia n Transform"


That is what the aforementioned key argument to sort is: a built-in
decorate-sort-undecorate.
lst = [[1,4],[3,9],[2,5],[3,2]]
print lst [[1, 4], [3, 9], [2, 5], [3, 2]] lst.sort(key=la mbda x: x[1])
print lst

[[3, 2], [1, 4], [2, 5], [3, 9]]

Neil
Nov 22 '05 #7
Neil Hodgson wrote:
Since no-one mentioned it and its a favourite of mine, you can use the
decorate-sort-undecorate method, or "Schwartzia n Transform"


That is what the aforementioned key argument to sort is: a built-in
decorate-sort-undecorate.


And crucially it is a built-in DSU which gets it right more often than
naive DSU implementations .

e.g. it is stable when you reverse the order:
lst = [[4,1],[4,2],[9,3],[5,4],[2,5]]
list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ])) [[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]] l1 = list(lst)
l1.sort(key=ope rator.itemgette r(0), reverse=True)
l1 [[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]]

and it gets incomparable objects right:
lst = [4+1j, 4+2j, 9+3j, 5+4j, 2+5j]
[ x[-1] for x in sorted([ (x.real,x) for x in lst ]) ]
Traceback (most recent call last):
File "<pyshell#3 9>", line 1, in -toplevel-
[ x[-1] for x in sorted([ (x.real,x) for x in lst ]) ]
TypeError: no ordering relation is defined for complex numbers l1 = list(lst)
l1.sort(key=ope rator.attrgette r('real'))
l1 [(2+5j), (4+1j), (4+2j), (5+4j), (9+3j)]

Nov 23 '05 #8

Duncan Booth wrote:
e.g. it is stable when you reverse the order:
lst = [[4,1],[4,2],[9,3],[5,4],[2,5]]
list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ])) [[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]] l1 = list(lst)
l1.sort(key=ope rator.itemgette r(0), reverse=True)
l1

[[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]]

Just curious, which one is supposed to be the right answer ? and why
the second one is preferable over the first one(if both is right,
assume we only care about x[0]).

Of course, there is no reason to DIY when the built-in can do the job.

Nov 23 '05 #9
bo****@gmail.co m wrote:
Duncan Booth wrote:
e.g. it is stable when you reverse the order:
>>> lst = [[4,1],[4,2],[9,3],[5,4],[2,5]]
>>> list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ]))

[[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]]
>>> l1 = list(lst)
>>> l1.sort(key=ope rator.itemgette r(0), reverse=True)
>>> l1

[[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]]

Just curious, which one is supposed to be the right answer ? and why
the second one is preferable over the first one(if both is right,
assume we only care about x[0]).

Of course, there is no reason to DIY when the built-in can do the job.


"Stability" means items with the same key preserve their relative position.
In the original list of the example [4, 1] and [4, 2] both have the same
key. Therefore [4, 1] should stay before [4, 2], so the second is the
"right" answer.

The practical advantage is that if e. g. you sort items first by color and
then by size, items of the same size will appear sorted by color. In
particular, sorting a list by the same key a second time does not change
the list.

Peter

Nov 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2561
by: Steve Pinard | last post by:
(Got a comm error trying to post first time, sorry if this is a duplicate) New to Python, so please bear with me. >>> import sys >>> print sys.modules.keys() # works fine >>> print sys.modules.keys().sort() # returns None, why? None
3
1619
by: Brian McGonigle | last post by:
I'm a Perl programmer learning Python (up to chapter 7 in Learning Python, so go easy on me :-) and I find that I look to do things in Python the way I would do them in Perl. In Perl functions and methods usually only return and undefined value in the event of an error, make an endless number of compound statements possible. Is there a version of sort() I could import from somewhere that returns a reference to the object on which it was...
12
2913
by: Eva | last post by:
Hi, I try to implement quick sort. I sort vectors by their first value. 10 2 3 4 9 3 5 6 10 4 5 6 must be 9 3 5 6 10 2 3 4 10 4 5 6 The prog works great on maybe 500 vectors, but I have an "Aborted(core
20
4054
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort†method. For example: li=;
1
12834
by: Booser | last post by:
// Merge sort using circular linked list // By Jason Hall <booser108@yahoo.com> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> //#define debug
11
1940
by: Leon | last post by:
I have six textbox controls on my webform that allows the user to enter any numbers from 1 to 25 in any order. However, I would like to sort those numbers from least to greatest before sending them to the database. How can accomplish this task? Thanks!
3
6433
by: Adam J. Schaff | last post by:
Hello. I recently noticed that the Sort method of the .NET ArrayList class does not behave as I expected. I expect 'A' < '_' < 'a' (as per their ascii values) but what I got was the opposite. Simple code: Dim y As New ArrayList y.Add("Abc") y.Add("abc") y.Add("_bc")
99
4632
by: Shi Mu | last post by:
Got confused by the following code: >>> a >>> b >>> c {1: , ], 2: ]} >>> c.append(b.sort()) >>> c {1: , ], 2: , None]}
0
1476
by: Amar | last post by:
Hi, I have a generic list with a some objects of a particular class in it. I have implemented a IComparer for the the class and pass it to the List. The list.sort method works fine when the value of the field I want to compare is different, but when all the elements are same, the list still gets sorted(meaning the sequence of the elements still change). For eg. Say the list is filled with object of type A, where in A has a property...
3
10550
by: raylopez99 | last post by:
This is an example of using multiple comparison criteria for IComparer/ Compare/CompareTo for List<and Array. Adapted from David Hayden's tutorial found on the net, but he used ArrayList so the format was different. Basically you can sort a class having members LastName (string), FirstName (string) and Age (int) according to whether you want to sort by Last Name, First Name or Age, using the .Sort function
0
8820
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8718
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8499
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8601
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5630
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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

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.