1

I've got a folder with a dataset which is poorly sorted, and id like to rearrange the information that I'm pulling from it as I'm reading it. Therefore I am wondering, is there an easy way to sort following input:

[['-10' '10']

 ['-10' '20']

 ['-15' '10']

 ['-15' '20']

 ['-5' '10']

 ['-5' '20]

 ['0' '10']

 ['0' '20']

 ['10' '10']

 ['10' '20']

 ['15' '10']

 ['15' '20']

 ['5' '10']

 ['5' '20]

into following output:

[['-15' '10']

 ['-15' '20']

 ['-10' '10']

 ['-10' '20']

 ['-5' '10']

 ['-5' '20]

 ['0' '10']

 ['0' '20']

 ['5' '10']

 ['5' '20]

 ['10' '10']

 ['10' '20']

 ['15' '10']

 ['15' '20']]
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

How about using pandas dataframe?

import pandas as pd

data = [['5', '10'], ['4', '20']]

dataframe = pd.DataFrame(data).sort_values(by=0) #define by as index

print(dataframe)

#Output:
#   0   1
#1  4  20
#0  5  10
pfuhlert
  • 533
  • 4
  • 16
-1

I'm afraid you'll need to cast your str values to int for the desired sort order. Then, you just want to sort a list by multiple attributes. If you want to have str values in the output, too, you'll also need to cast backwards.

import operator

a = [['-10', '10'],
     ['-10', '20'],
     ['-15', '10'],
     ['-15', '20'],
     ['-5', '10'],
     ['-5', '20'],
     ['0', '10'],
     ['0', '20'],
     ['10', '10'],
     ['10', '20'],
     ['15', '10'],
     ['15', '20'],
     ['5', '10'],
     ['5', '20']]

print(a)

b = [[int(e[0]), int(e[1])] for e in a]         # to int
b = sorted(b, key=operator.itemgetter(0, 1))    # sort
b = [[str(e[0]), str(e[1])] for e in b]         # to str

print(b)

Output:

[['-10', '10'], ['-10', '20'], ['-15', '10'], ['-15', '20'], ['-5', '10'], ['-5', '20'], ['0', '10'], ['0', '20'], ['10', '10'], ['10', '20'], ['15', '10'], ['15', '20'], ['5', '10'], ['5', '20']]
[['-15', '10'], ['-15', '20'], ['-10', '10'], ['-10', '20'], ['-5', '10'], ['-5', '20'], ['0', '10'], ['0', '20'], ['5', '10'], ['5', '20'], ['10', '10'], ['10', '20'], ['15', '10'], ['15', '20']]

Hope that helps!


EDIT: Or just use some lambda expression in sorted:

c = sorted(a, key = lambda x: (int(x[0]), int(x[1])))
print(c)
HansHirse
  • 18,010
  • 10
  • 38
  • 67