[portland] Sorting A List of Tuples
kirby urner
kirby.urner at gmail.com
Thu Nov 8 18:52:59 CET 2007
Hi Rich --
The list.sort() method takes an optional 'key' argument that'd be a
function, which you might use to pick out the value you want to
compare, as follows:
IDLE 1.2.1
>>> mylist = [(1,2,3), (8,1,7), (8,5,2)]
>>> def f(x):
return x[1]
>>> mylist.sort(key=f)
>>> mylist
[(8, 1, 7), (1, 2, 3), (8, 5, 2)]
Or just use lambda in this case:
>>> mylist = [(1,2,3), (8,1,7), (8,5,2)]
>>> mylist.sort(key=lambda x: x[1])
>>> mylist
[(8, 1, 7), (1, 2, 3), (8, 5, 2)]
Kirby
On Nov 8, 2007 9:25 AM, Rich Shepard <rshepard at appl-ecosys.com> wrote:
> All the information I find on sorting lists assumes the list has only a
> single value to be sorted. What to do with multiple values when the sort is
> on the second or third item and all must be kept together?
>
> I have lists of tuples which I'd like to sort on the second item while
> retaining the relationships among the item pairs.
>
> Could I do
> terms.sort([][1])
> ?
>
> A pointer to a reference would be fine.
>
> Rich
>
> --
> Richard B. Shepard, Ph.D. | Integrity Credibility
> Applied Ecosystem Services, Inc. | Innovation
> <http://www.appl-ecosys.com> Voice: 503-667-4517 Fax: 503-667-8863
> _______________________________________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/mailman/listinfo/portland
>
More information about the Portland
mailing list