Python Forum
sorting a 2 dimensional array
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorting a 2 dimensional array
#1
Hey Folks,

i want to sort an array by numbers, like this array for example


[['B', '-50', '-30', '-8', '1000'], 
    ['T', '-60', '-180', '0', 'parts.dat'], 
    ['T', '-160', '-160', '0', '40']]
Now I want to sort the array by the second or third character, any of you has a idea how to?
I tried this code to sort the array, but now I have the problem that it doesn't work with the letters in my data.


 data = [[int(c) for c in row] for row in data]
    data = sorted(tokenized, key=lambda x: x[1])
    print(data)
Hope anyone can help me with this :)

Kind reguards,

M.D.B.
Reply
#2
a = [['B', '-50', '-30', '-8', '1000'],
    ['T', '-60', '-180', '0', 'parts.dat'],
    ['T', '-160', '-160', '0', '40']]

a.sort(key=lambda k: int(k[1]))
for i in a:
    print(i)

sort by third and then second
a.sort(key=lambda k: (int(k[2]), int(k[1])))
99 percent of computer problems exists between chair and keyboard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to quantize a 4 dimensional array? PythonNPC 2 1,717 Apr-23-2022, 04:34 PM
Last Post: Gribouillis
  How to create 2 dimensional variables in Python? plumberpy 5 2,007 Mar-31-2022, 03:15 AM
Last Post: plumberpy
  Slicing a 2 dimensional array Scott 2 1,732 Jan-12-2022, 07:18 AM
Last Post: paul18fr
  Problem using two-dimensional interpolation. Result looks bad player1682 4 2,624 Oct-12-2021, 09:27 AM
Last Post: player1682
  Index data must be 1-dimensional : Classifier with sklearn Salma 0 4,428 Apr-01-2021, 03:22 PM
Last Post: Salma
  2 Dimensional Arrays Prithak 4 2,707 Mar-21-2021, 09:35 PM
Last Post: deanhystad
  comparing 2 dimensional list glennford49 10 4,302 Mar-24-2020, 05:23 PM
Last Post: saikiran
  Python 2 dimensional array creations sharpe 1 2,049 Nov-24-2019, 10:33 AM
Last Post: ThomasL
  Sorting a copied list is also sorting the original list ? SN_YAZER 3 3,250 Apr-11-2019, 05:10 PM
Last Post: SN_YAZER
  Python: Creating N Dimensional Grid jf451 0 2,385 Dec-06-2018, 10:53 PM
Last Post: jf451

Forum Jump:

User Panel Messages

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