best Pythonic way to do this sort: Python newb

Paul Rubin http
Mon Oct 10 01:26:13 EDT 2005


"Sean Berry" <sean at buildingonline.com> writes:
> > def get_key(x): return x[2]
> > sorted_list = sorted(myList, key=get_key)
> 
> Sorry if I am missing something.  But. what is sorted here?

sorted is a built-in function that sorts the thing that you pass it.
It just appeared in Python 2.4, I think.  With older versions, yeah,
you have to use the .sort method that sorts in place.

> I tried doing the following... with no luck so far
> myList.sort(lambda x, y: cmp(myFunction(x[2]), myFunction(y[2]))

That looks ok to me.

>>> x = [(i,i*i,1 + 17*i**2 - i**3) for i in range(20)]
>>> x
[(0, 0, 1), (1, 1, 17), (2, 4, 61), (3, 9, 127), (4, 16, 209), (5, 25,
301), (6, 36, 397), (7, 49, 491), (8, 64, 577), (9, 81, 649), (10,
100, 701), (11, 121, 727), (12, 144, 721), (13, 169, 677), (14, 196,
589), (15, 225, 451), (16, 256, 257), (17, 289, 1), (18, 324, -323),
(19, 361, -721)]
>>> x.sort(lambda a,b:cmp(a[2],b[2]))
>>> x
[(19, 361, -721), (18, 324, -323), (0, 0, 1), (17, 289, 1), (1, 1,
17), (2, 4, 61), (3, 9, 127), (4, 16, 209), (16, 256, 257), (5, 25,
301), (6, 36, 397), (15, 225, 451), (7, 49, 491), (8, 64, 577), (14,
196, 589), (9, 81, 649), (13, 169, 677), (10, 100, 701), (12, 144,
721), (11, 121, 727)]
>>>



More information about the Python-list mailing list