Doubt regarding sorting of a list specific field
Steven Bethard
steven.bethard at gmail.com
Wed Apr 13 03:27:20 EDT 2005
F. Petitjean wrote:
> Le Wed, 13 Apr 2005 01:13:40 -0600, Steven Bethard a écrit :
>
>>praba kar wrote:
>>
>>>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:
>>
>>STeVe
>
> nice explaination. But, if the items of the list are tuples the default
> rule for comparing tuples is such that
> seq.sort()
> would be sufficient here.
See my other post in this thread. seq.sort() is not stable; if the OP's
list looked like:
[(1234,'name3'), (1234,'name1')]
then calling seq.sort() would give
[(1234,'name1'), (1234,'name3')]
instead of
[(1234,'name3'), (1234,'name1')]
which is what I assumed the OP wanted when he said "I want to sort only
numeric value".
STeVe
More information about the Python-list
mailing list