473,385 Members | 1,661 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,385 software developers and data experts.

Sorting lists

asc
Hi all,
I have a problem and I'm not sure whether sort() can help me.
I understand that if I have a list; say L = ['b', 'c', 'a']
I can use L.sort() and I will then have; L = ['a', 'b', 'c']

But my problem is this. I have a list, that contains a number of
embeded lists;
e.g. L2 = [['something', 'bb'], ['somethingElse', 'cc'],
['anotherThing', 'aa']]
Now I want to sort this list by the second item of each sublist. So
the outcome I would like is;
L2 = [['anotherThing', 'aa'], ['something', 'bb'], ['somethingElse',
'cc']]

Is there a way I can use sort for this? Or am I going to have write a
custom function to sort this out?

Many thanks.
Nov 17 '08 #1
5 1959
On Nov 17, 8:56*pm, asc <adam.cheas...@gmail.comwrote:
But my problem is this. I have a list, that contains a number of
embeded lists;
e.g. L2 = [['something', 'bb'], ['somethingElse', 'cc'],
['anotherThing', 'aa']]
Now I want to sort this list by the second item of each sublist. So
the outcome I would like is;
L2 = [['anotherThing', 'aa'], ['something', 'bb'], ['somethingElse',
'cc']]

Is there a way I can use sort for this?
Yes. Read the manual. Look for the key argument. You need to make up a
function (using def or lambda) that will pluck the desired sort-key
out of a sub-list.
Nov 17 '08 #2
On Mon, Nov 17, 2008 at 1:56 AM, asc <ad***********@gmail.comwrote:
Hi all,
I have a problem and I'm not sure whether sort() can help me.
I understand that if I have a list; say L = ['b', 'c', 'a']
I can use L.sort() and I will then have; L = ['a', 'b', 'c']

But my problem is this. I have a list, that contains a number of
embeded lists;
e.g. L2 = [['something', 'bb'], ['somethingElse', 'cc'],
['anotherThing', 'aa']]
Now I want to sort this list by the second item of each sublist. So
the outcome I would like is;
L2 = [['anotherThing', 'aa'], ['something', 'bb'], ['somethingElse',
'cc']]

Is there a way I can use sort for this? Or am I going to have write a
custom function to sort this out?
You use the `key` argument to .sort():

L2.sort(key=lambda item: item[1])

This sorts L2 by the result of applying the `key` function to each of
the items. Behind the scenes, I believe it does a Schwartzian
transform.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com
>
Many thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Nov 17 '08 #3
Chris Rebert:
You use the `key` argument to .sort():
L2.sort(key=lambda item: item[1])
I like the lambda because it's a very readable solution that doesn't
require the std lib and it doesn't force the programmer (and the
person that reads the code) to learn yet another thing/function.

But I can suggest to also look for operator.itemgetter.

------------
In C# a syntax for lambdas may become a little shorter, but the
parsing may become less easy:
L2.sort(key = sub =sub[1])

In Mathematica they use the & to define lambdas, and #1, #2, etc, to
denote the arguments.

Bye,
bearophile
Nov 17 '08 #4
be************@lycos.com wrote:
Chris Rebert:
>You use the `key` argument to .sort():
L2.sort(key=lambda item: item[1])

I like the lambda because it's a very readable solution that doesn't
require the std lib and it doesn't force the programmer (and the
person that reads the code) to learn yet another thing/function.

But I can suggest to also look for operator.itemgetter.
Since itemgetter is builtin, it will probably run faster, though the
O(nlogn) time for sorting will override the O(n) time for key calls.

Nov 17 '08 #5
On Mon, 17 Nov 2008 14:36:03 -0500, Terry Reedy wrote:
be************@lycos.com wrote:
>Chris Rebert:
>>You use the `key` argument to .sort(): L2.sort(key=lambda item:
item[1])

I like the lambda because it's a very readable solution that doesn't
require the std lib and it doesn't force the programmer (and the person
that reads the code) to learn yet another thing/function.

But I can suggest to also look for operator.itemgetter.

Since itemgetter is builtin, it will probably run faster, though the
O(nlogn) time for sorting will override the O(n) time for key calls.
Well, eventually, for large enough lists, sure. But if the constants are
sufficiently different, the key calls may be the bottleneck. O(foo)
analysis is valuable, but it isn't the full story. A fast enough O(n**2)
algorithm might be preferable to a slow O(log n) algorithm for any data
you're interested in.

To give an extreme example, suppose your itemgetter function (not the
Python built-in!) had to query some remote database over the internet. It
might be O(n) but the multiplicative constant would be so large that the
time taken to get items far dominates the time to sort the list, unless
the list is *seriously* huge:

(Say) sorting takes O(n*log n) with multiplicative constant of 1e-5.
Item getting takes O(n) with multiplicative constant of 1.

Then the time taken to sort doesn't become larger than the time taken to
get the items until approximately:

1e-5*n*log(n) n
1e-5*log(n) 1
log(n) 1e5
n 2**100000

which is pretty big... for any reasonable-sized list, the O(n) part
dominates despite the asymptotic behaviour being O(n*log n).

--
Steven
Nov 18 '08 #6

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

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
10
by: Philippe C. Martin | last post by:
Hi, I'm looking for an easy algorithm - maybe Python can help: I start with X lists which intial sort is based on list #1. I want to reverse sort list #1 and have all other lists sorted...
2
by: Kakarot | last post by:
I'm gona be very honest here, I suck at programming, *especially* at C++. It's funny because I actually like the idea of programming ... normally what I like I'm atleast decent at. But C++ is a...
7
by: Foodbank | last post by:
Hi everyone. I'm having trouble with this radix sorting program. I've gotten some of it coded except for the actual sorting :( The book I'm teaching myself with (Data Structures Using C and...
25
by: Dan Stromberg | last post by:
Hi folks. Python appears to have a good sort method, but when sorting array elements that are very large, and hence have very expensive compares, is there some sort of already-available sort...
4
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event...
2
by: Susan.Adkins | last post by:
Alright, I must say that the problem my teacher has given us to do has royally annoyed me. We are to take a letter *txt file* and then read in the words. Make 2 seperate lists *even and odd* for...
16
by: Kittyhawk | last post by:
I would like to sort an Arraylist of objects on multiple properties. For instance, I have a Sort Index property and an ID property (both integers). So, the results of my sort would look like this:...
20
by: martin-g | last post by:
Hi. Mostly I program in C++, and I'm not fluent in C# and .NET. In my last project I began to use LinkedList<and suddenly noticed that can't find a way to sort it. Does it mean I must implement...
7
by: apotheos | last post by:
I can't seem to get this nailed down and I thought I'd toss it out there as, by gosh, its got to be something simple I'm missing. I have two different database tables of events that use different...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.