1

Possible Duplicate:
How to sort (list/tuple) of lists/tuples?

I have a list of tuples that i want to sort in numerical order by the second value in the tuple. A sample of the list im working with is:

[('H2O', '6'), ('O2', '4')]

so what i would want in this case is:

[('O2','4'),('H2O',6')]

I know this is really basic I just can seem to figure it out.

Community
  • 1
  • 1
user1698174
  • 469
  • 2
  • 5
  • 9
  • 1
    Your question has nothing to do with chemicals and coefficients, if you try to express the problem in a more general way then you are more likely to find an answer to your question. – bcoughlan Dec 18 '12 at 18:11

4 Answers4

7

Use the key parameter of sort:

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

This will convert the second element in the tuple to an integer, and sort by these integers.

Since your tuples contain numbers in the second element, it makes more sense to store numbers in the tuples rather than strings. If you do so, you can sort with:

import operator
mylist.sort(key = operator.itemgetter(1))
interjay
  • 107,303
  • 21
  • 270
  • 254
3
>>> l = [('H2O', '6'), ('O2', '4')]
>>> l.sort(key = lambda x: int(x[1]))
>>> l
[('O2', '4'), ('H2O', '6')]

sort method does in-place sorting, and hence modifies your list.

You can also use sorted function, which returns the sorted list while leaving the original list unmodified.

>>> sorted(l, key=lambda x: int(x[1]))
[('O2', '4'), ('H2O', '6')]
>>> l
[('H2O', '6'), ('O2', '4')]  # Original list unmodified

Often we use sorted function, if we want to iterate over a sorted list.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

You need to use the key argument of sort (or sorted). It is a function that is passed every element of the iterable (in this case, each tuple).

You can use operator.itemgetter...

In [1]: import operator

In [2]: chem = [('H2O', '6'), ('O2', '4')]

In [3]: sorted(chem, key=operator.itemgetter(1))
Out[3]: [('O2', '4'), ('H2O', '6')]

or a simple function:

In [4]: sorted(chem, key=lambda x: x[1])
Out[4]: [('O2', '4'), ('H2O', '6')]

Edit: interjay is right: it's better to convert the second item to a number:

sorted(chem, key=lambda x: int(x[1]))

Otherwise they will be sorted alphabetically.

Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
0

you have to first import operator Now use the key parameter to list.sort():

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

For faster,

list.sort(key=operator.itemgetter(1))
Harsh Kothari
  • 311
  • 3
  • 4