Home > Software design >  Sorting Nested Lists with Various Elements
Sorting Nested Lists with Various Elements

Time:12-04

I have a nested list like:

[["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]]

I need to have this sorted by x (from least to most) as (other strings should stay where they are):

[["bla","x=13","z=13","blabla"],["bla","blabla","x=17"],["x=27","blabla","bla","y=24"]]

and also from most to least:

[["x=27","blabla","bla","y=24"],["bla","blabla","x=17"],["bla","x=13","z=13","blabla"]]

I think I have to use key=lambda but I just couldn't figure out how to do it. Searched through the web and this website but I just can't do it.

CodePudding user response:

Given your list:

sort_this_list = [
    ["bla","blabla","x=17"],
    ["bla","x=13","z=13","blabla"],
    ["x=27","blabla","bla","y=24"]
]

First, extract the x element from the respective list!

def get_x(list):
    # Iterate over the items in the given list
    for item in list:
        # Check if the item starts with "x="
        if item.startswith("x="):
            # Extract the value of x and return it as an integer
            return int(item.split("=")[1])

Now you can sort it via sorted_ascending = sorted(sort_this_list, key=get_x) (Look up the sorted(..) function: This will return it ascending as you requested it.)!

CodePudding user response:

Just for the sake of it, here's one with a lambda function:

mylist = [["bla","blabla","x=17"],["bla","x=13","z=13","blabla"],["x=27","blabla","bla","y=24"]]

mylist.sort(key = lambda l:int([item for item in l if 'x=' in item][0].split('=')[1]), reverse = True)

# [['x=27', 'blabla', 'bla', 'y=24'],
#  ['bla', 'blabla', 'x=17'],
#  ['bla', 'x=13', 'z=13', 'blabla']]
  • Related