dimitrisGmk
dimitrisGmk

Reputation: 79

Python sort an array

I'm trying to sort a numpy array containing classes from a variable.

groups =['(0, 10]', '(10, 20]', '(100, 110]', '(110, 120]', '(120, 130]',
         '(130, 140]', '(140, 150]', '(150, 160]', '(160, 170]', '(170, 180]', 
         '(180, 190]', '(190, 200]', '(20, 30]', '(200, 210]', '(210, 220]', 
         '(230, 240]', '(30, 40]', '(40, 50]', '(50, 60]', '(60, 70]', 
         '(70, 80]', '(80, 90]', '(90, 100]']

I want this:

groups = ['(0, 10]', '(10, 20]','(30, 40]','(40, 50]', '(50, 60]', ...]

I tried this:

sort(groups)

but nothing........

Upvotes: 2

Views: 960

Answers (3)

Patrick Haugh
Patrick Haugh

Reputation: 60974

The sorting function is sorted. We'll use a key function to extract the numbers and convert them to a tuple of integers.

sorted(groups, key=lambda x: tuple(map(int, x[1:-1].split(','))))

Output:

['(0, 10]', '(10, 20]', '(20, 30]', '(30, 40]', '(40, 50]', '(50, 60]',
 '(60, 70]', '(70, 80]', '(80, 90]', '(90, 100]', '(100, 110]', '(110, 120]',
'(120, 130]', '(130, 140]', '(140, 150]', '(150, 160]', '(160, 170]', 
'(170, 180]', '(180, 190]', '(190, 200]', '(200, 210]', '(210, 220]', '(230, 240]']

Upvotes: 4

MSeifert
MSeifert

Reputation: 152647

You have to interpret your strings as tuples of numbers otherwise they will be sorted by lexicographical order (which would give the wrong result!):

def interpret_as_tuple(x):
    splitted = x.split(',')
    first = int(splitted[0].strip('( '))
    second = int(splitted[1].strip('] '))
    return first, second

groups.sort(key=interpret_as_tuple)

groups

returns:

['(0, 10]', '(10, 20]', '(20, 30]', '(30, 40]', '(40, 50]', '(50, 60]', '(60, 70]',
 '(70, 80]', '(80, 90]', '(90, 100]', '(100, 110]', '(110, 120]', '(120, 130]',
 '(130, 140]', '(140, 150]', '(150, 160]', '(160, 170]', '(170, 180]', '(180, 190]',
 '(190, 200]', '(200, 210]', '(210, 220]', '(230, 240]']

Upvotes: 2

blue note
blue note

Reputation: 29071

There are two problems with your elements

  • they are strings, not tuples of numbers
  • the closing ] does not match the opening (

So, you first have to convert them

groups = [eval(group[:-1] + ')') for group in groups]
print(sorted(groups))

Upvotes: -3

Related Questions