0

How do you sort a list by elemant thats a tuple? Let say below is the list LL. I want to sort ID2 -- LL[1] which is a tuple as asc. How would I do it.

           Id,  Id2    CCC
           A123 A120 '2011-03'
  LL=      A133 A123 '2011-03'
           D123 D120 '2011-04'
           D140 D123 '2011-04'
1
  • ID2 -- LL[1] which is a tuple as asc - what? Commented Apr 24, 2011 at 20:54

2 Answers 2

4

Have a look at http://wiki.python.org/moin/HowTo/Sorting/

sorted(LL, key=itemgetter(1)) might do what you want.

Please note that you have to from operator import itemgetter to get the itemgetter function.

In [1]: LL = (('A123', 'A120', '2011-03'), ('A133', 'A123', '2011-03'), ('D123', 'D120', '2011-04'), ('D140', 'D123', '2011-04'))

In [2]: from operator import itemgetter

In [3]: sorted(LL, key=itemgetter(1))
Out[3]:
[('A123', 'A120', '2011-03'),
 ('A133', 'A123', '2011-03'),
 ('D123', 'D120', '2011-04'),
 ('D140', 'D123', '2011-04')]
Sign up to request clarification or add additional context in comments.

3 Comments

Does it matter that key=itemgetter(1) is a tuple
key=itemgetter(1) will make sorted() fetch the item with index 1 from each element in LL. Please actually read the page I linked to, it explains it: wiki.python.org/moin/HowTo/Sorting/#Operator_Module_Functions
I have been trying to figure this out for a while . I found my prob. The database has the sorted col as Primary Key which keeps changing my order. ;-)))))! thanks
0

You can go for:

LL.sort(key=lambda x:x[1])

Where 1 is the index of the element of the tupple.

1 Comment

Better use itemgetter(1) from the operator module. Otherwise a python function needs to be called for every item (the operator functions are written in C if you are using the default CPython implementation)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.