Python Forum
Sorting nested lists in ascending order
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting nested lists in ascending order
#1
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
Reply
#2
Please use proper code tags while coding, it is very difficult to understand your code otherwise. See BBCode for more info
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
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]]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,248 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Input validation for nested dict and sorting list of tuples ranbarr 3 3,841 May-14-2021, 07:14 AM
Last Post: perfringo
  Recursions with nested lists sashiessay 2 2,730 Oct-05-2019, 11:40 AM
Last Post: sashiessay
  Sum of Nested Lists raifuru42 2 4,314 Feb-19-2018, 02:57 PM
Last Post: mckingstar
  Combine nested lists in output python12345 2 2,749 Feb-17-2018, 01:38 PM
Last Post: python12345
  Nested loops, lists and if statements Liquid_Ocelot 10 8,865 Apr-23-2017, 02:02 PM
Last Post: Mekire

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020