Welcome, guest | Sign In | My Account | Store | Cart

Sort recursively nested lists

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
"""
recursive sort
"""

def rec_sort(iterable):
    # if iterable is a mutable sequence type
    # sort it
    try:
        iterable.sort()
    # if it isn't return item
    except:
        return iterable
    # loop inside sequence items
    for pos,item in enumerate(iterable):
        iterable[pos] = rec_sort(item)
    return iterable


if __name__ == '__main__':

    struct = [[1,2,3,[6,4,5]],[2,1,5],[4,3,2]]
    print rec_sort(struct)
Created by Nicola Muneratto on Fri, 20 Jan 2006 (PSF)
Python recipes (4591)
Nicola Muneratto's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks