vincent wehren wrote:
"praba kar" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED]
| Dear All,
|
| I have doubt regarding sorting. I have a list
| that list have another list (eg)
|
| list = [[1234,'name1'],[2234,'name2'],[0432,'name3']]


-> Be careful, 0432 is octal notation for 282.
|
| I want to sort only numeric value having array field.
| How I need to do for that.

You may want use the decorate-sort-undecorate idiom.
I othere words, you isolate the index you want to sort by,
sort on the indices, than get rid of the indices again.

Something like:

def sortSeqOfSeqs(seq, idx):
    tmp = sorted([(elem[idx], elem) for elem in seq])
    return [elem[1] for elem in tmp]

Note that this is not stable:

py> seq = [(1,'c'),(1,'b')]
py> [tup[1] for tup in sorted((x[0], x) for x in seq)]
[(1, 'b'), (1, 'c')]

Which should not have reordered the list since 1 == 1. If you want a stable version, you could use:

py> [tup[2] for tup in sorted((x[0], i, x) for i, x in enumerate(seq))]
[(1, 'c'), (1, 'b')]

But that seems pretty silly. You're already using Python 2.4 features (e.g. sorted), so you might as well use the key argument to sorted:

py> sorted(seq, key=operator.itemgetter(0))
[(1, 'c'), (1, 'b')]

Note if you're not using 2.4, you may want to use the decorate-sort-undecorate pattern like:

py> decorated_seq = [(x[0], i, x) for i, x in enumerate(seq)]
py> decorated_seq.sort()
py> [tup[2] for tup in decorated_seq]
[(1, 'c'), (1, 'b')]

But personally, I'd just upgrade. ;)

STeVe
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to