faqts : Computers : Programming : Languages : Python : Snippets : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

0 of 1 people (0%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

How can I sort a list efficiently if each element can be understood as a vector?

Jan 22nd, 2008 11:51
stephen brown, Monika Wiemann,


Both the list.sort() method (which sorts a list in place) and the
sorted() built-in function (which returns a new, sorted list) can be
provided with a custom cmp() function, to compare two elements, or a
key() function, which converts an element to a sorting key.  key() is
more efficient than cmp().  It depends on what you mean by vector, but
most kinds have a length which can be used for the key.  Using a
conventional norm for the key(), and two element vectors:
>>> v = [(2,2), (1,3), (0,0), (-1,-1), (0,1)]
>>> key_function = lambda x: x[0]*x[0]+x[1]*x[1]
>>> v.sort(key=key_function)
>>> v
[(0, 0), (0, 1), (-1, -1), (2, 2), (1, 3)]
>>>