开发者

Sorting while preserving order in python

What is the best way to sort a list of floats by their value, whiles still keeping record of the initial order.

I.e. sorting a:

a=[2.3, 1.23, 3.4, 0.4]

returns something like

a_sorted = [0.4, 1.23, 2.3, 3.4]
a_order = [4, 2, 1, 3开发者_运维技巧]

If you catch my drift.


You could do something like this:

>>> sorted(enumerate(a), key=lambda x: x[1])
[(3, 0.4), (1, 1.23), (0, 2.3), (2, 3.4)]

If you need to indexing to start with 1 instead of 0, enumerate accepts the second parameter.


  • Use enumerate to generate the sequence numbers.
  • Use sorted with a key to sort by the floats
  • Use zip to separate out the order from the values

For example:

a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))


If you have numpy installed:

import numpy
a=[2.3, 1.23, 3.4, 0.4]
a_sorted = numpy.sorted(a)
a_order = numpy.argsort(a)


from itertools import izip
a_order, a_sorted = [list(b) for b in izip(*sorted(enumerate(a, 1), key=lambda n: n[1]))]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜