4.10. order_by_index()

natsort.order_by_index(seq, index, iter=False)

Order a given sequence by an index sequence.

The output of index_natsorted is a sequence of integers (index) that correspond to how its input sequence would be sorted. The idea is that this index can be used to reorder multiple sequences by the sorted order of the first sequence. This function is a convenient wrapper to apply this ordering to a sequence.

  • seq (sequence) – The sequence to order.
  • index (iterable) – The iterable that indicates how to order seq. It should be the same length as seq and consist of integers only.
  • iter ({True, False}, optional) – If True, the ordered sequence is returned as a iterator; otherwise it is returned as a list. The default is False.

out – The sequence ordered by index, as a list or as an iterator (depending on the value of iter).

Return type:

{list, iterator}


order_by_index is a convenience function that helps you apply the result of index_natsorted:

>>> a = ['num3', 'num5', 'num2']
>>> b = ['foo', 'bar', 'baz']
>>> index = index_natsorted(a)
>>> index
[2, 0, 1]
>>> # Sort both lists by the sort order of a
>>> order_by_index(a, index)
['num2', 'num3', 'num5']
>>> order_by_index(b, index)
['baz', 'foo', 'bar']