Doubt regarding sorting of a list specific field

Steven Bethard steven.bethard at gmail.com
Wed Apr 13 03:13:40 EDT 2005


praba kar wrote:
>     I have doubt regarding sorting. I have a list
> that list have another list (eg)
> 
> list = [[1234,'name1'],[2234,'name2'],[0432,'name3']]
> 
> I want to sort only numeric value having array field.
> How I need to do for that. 

In Python 2.4:

py> import operator
py> seq = [(1234,'name1'),(2234,'name2'),(1432,'name3')]
py> seq.sort(key=operator.itemgetter(0))
py> seq
[(1234, 'name1'), (1432, 'name3'), (2234, 'name2')]

Note that I've changed your name 'list' to 'seq' since 'list' is 
shadowing the builtin list function in your code, and I've changed your 
nested lists to tuples because they look like groups of differently 
typed objects, not sequences of similarly typed objects.  See:

http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types

That said, the code I've given will still work if you shadow the builtin 
list or if you use lists instead of tuples.

STeVe



More information about the Python-list mailing list