Jump to content

Sorting 2d-list numerically

WiltedROck23

Current input is

lst = [['13', '4', '17'], ['30', '6', '5'], ['12', '37', '10']]

I would like to sort it like this

lst = [['4', '13', '17'], ['5', '6', '30'], ['10', '12', '37']]

 

Any ideas

wait i think i got it

 

for sublist in lst:
   sublist.sort()

print(lst)

 

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Do you need to make your own algorithm?

Nearly all programming languages will have some like .Sort() or similar to sort arrays.

 

If you do need to make your own algorhitm, I would recommend you read up on all the different types of sorting methods: https://en.wikipedia.org/wiki/Sorting_algorithm#Popular_sorting_algorithms

Typically people use insertion, quick or selection sort as a simple sorting algorithm, but there are many many options.

"We're all in this together, might as well be friends" Tom, Toonami.

 

mini eLiXiVy: my open source 65% mechanical PCB, a build log, PCB anatomy and discussing open source licenses: https://linustechtips.com/topic/1366493-elixivy-a-65-mechanical-keyboard-build-log-pcb-anatomy-and-how-i-open-sourced-this-project/

 

mini_cardboard: a 4% keyboard build log and how keyboards workhttps://linustechtips.com/topic/1328547-mini_cardboard-a-4-keyboard-build-log-and-how-keyboards-work/

Link to comment
Share on other sites

Link to post
Share on other sites

So I notice that your arrays are string arrays, first transform your arrays in int arrays

 

You can use a for, but I will use a map and lambda function:

 

lst = [['13', '4', '17'], ['30', '6', '5'], ['12', '37', '10']]

newList = map(lambda x: list(map(lambda y: int(y), x)), lst)

Now you can use the sorted() function to sort your array, again you can do it with a for, but I prefer a map and lambda function like this:

result = list(map(lambda x: sorted(x), newList))

 

Also this can be only one line like this:

result = list(map(lambda x: sorted(x), map(lambda x: list(map(lambda y: int(y), x)), lst)))

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×