Python Forum

Full Version: Sorting nested lists in ascending order
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,
I need some help with writing a function that takes ones argument (list) and sorts out nested lists in ascending order.

This is what I have so far, but it does not work with different examples:

def sortMatrix(m):
    for i in m:
        for e in range(1, len(i)):
            key = i[1]
            j = e - 1
            while j >= 0 and key < i[j]:
                i[j + 1] = i[j]
                j -= 1
            i[j + 1] = key

    for i in range(1, len(m)):
        s = m[1]
        t = i - 1
        while t >= 0 and s < m[t]:
            m[t + 1] = m[t]
            t -= 1
        m[t + 1] = s
        return (m)

m = [[5, 4], [2, 3], [6, 7]]
print(sortMatrix(m))
tests lists:

m = [[8, 9], [4, 6], [3, 2]]
m = [[5, 4], [2, 3], [6, 7]]
m = [[0, 1], [3, 5], [9, 8]]
Expected outcome (in the same order as above):

Output:
[[2, 3], [4, 6], [8, 9]] [[2, 3], [4, 5], [6, 7]] [[0, 1], [3, 5], [8, 9]]
Why my code is not working with first test as expected and how can I fix it?

Thanks a lot in advance
Please use proper code tags while coding, it is very difficult to understand your code otherwise. See BBCode for more info
Python has a function that does this, called sorted().
Type help(sorted) and you get
Output:
sorted(iterable, /, *, key=None, reverse=False) Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
So, if you are allowed to use this built in function, your code could be like
inlist = [[8, 9], [4, 6], [3, 2]]
print(sorted(inlist))
Output:
[[3, 2], [4, 6], [8, 9]]