473,395 Members | 1,488 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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 1650
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 "Schwartzian 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 "Schwartzian 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=lambda 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 "Schwartzian 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=operator.itemgetter(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#39>", 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=operator.attrgetter('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=operator.itemgetter(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.com 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=operator.itemgetter(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

Peter Otten wrote:
bo****@gmail.com 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=operator.itemgetter(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.

Ah, thanks. That clear things up.

Nov 23 '05 #11
Neil Hodgson <ny*****************@gmail.com> wrote:
Nick Craig-Wood:
Since no-one mentioned it and its a favourite of mine, you can use the
decorate-sort-undecorate method, or "Schwartzian Transform"


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


Its also python 2.4 only though :-(

(We are stuck on python 2.3 here)

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Nov 23 '05 #12

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

Similar topics

5
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 >>>...
3
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...
12
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...
20
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: ...
1
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
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...
3
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....
99
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
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...
3
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...

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.