Home > Software engineering >  How to sort list by a parameter?
How to sort list by a parameter?

Time:01-08

How do I sort the list by the first and second parameter?

lista=[]
f=open("eloadas.txt", "r")
for sor in f:
    sor=sor.strip().split()
    lista.append(sor)
lista.sort()

print("\n".join(map(lambda k:" ".join(k), lista)))

This is the script so far and I wanna sort this list:

enter image description here

To be like this:

enter image description here

CodePudding user response:

you can use the key argument in the sort method

lista.sort(key = lambda entry: entry[:2])

this will make the sort function use the first 2 values in the list for the sorting

CodePudding user response:

Assuming that your data is a list of lists (like in the code bellow) you can use the sorted() function and specify a key function that takes an inner list as input and returns a tuple of the values that you want to sort on.

lst = [[1, 34, 5, "foo"], [1, 32, 1, "bar"], [2, 33, 7, "dee"]]  # your data
sorted_lst = sorted(lst, key=lambda x: (x[0], x[1]))


print(sorted_lst)  # [[1, 32, 1, "bar"], [1, 34, 5, "foo"], [2, 33, 7, "dee"]]
  • Related