Long_NgV
Long_NgV

Reputation: 475

Sort the Interval in the correct order

rigt now I'm having this list of Interval

test = ['(0.556, 1.389]', '(0.192, 0.386]', '(0.386, 0.556]', '(-0.759, -0.401]', '(-0.401, -0.064]', '(-0.064, 0.192]', '(-1.34, -0.759]']

I want to sort them into the correct order, I have tried these code:

test.sort()
sorted(test, key=lambda l:l[0])

However the results are not correct:

test = ['(-0.064, 0.192]', '(-0.401, -0.064]', '(-0.759, -0.401]', '(-1.34, -0.759]', '(0.192, 0.386]', '(0.386, 0.556]', '(0.556, 1.389]']

I just to to have a list that are sorted in order, like this:

test = ['(-1.34, -0.759]', '(-0.759, -0.401]', '(-0.401, -0.064]', '(-0.064, 0.192]', '(0.192, 0.386]', '(0.386, 0.556]', '(0.556, 1.389]']

Upvotes: 2

Views: 497

Answers (1)

trotta
trotta

Reputation: 1226

As mentioned in the comments, your list elements are strings. One way to solve your problem would be to convert them to tuples and sort the list of tuples afterwards:

import ast

test = ['(0.556, 1.389]', '(0.192, 0.386]', '(0.386, 0.556]', '(-0.759, -0.401]', '(-0.401, -0.064]', '(-0.064, 0.192]', '(-1.34, -0.759]']

new_list = []

for x in test:
    a = x.replace(']', ')')
    b = ast.literal_eval(a)
    new_list.append(b)

new_list = sorted(new_list, key=lambda l:l[0])
print(new_list)
# [(-1.34, -0.759), (-0.759, -0.401), (-0.401, -0.064), (-0.064, 0.192), (0.192, 0.386), (0.386, 0.556), (0.556, 1.389)]

This snippet takes your list, replaces the ] at the end of every string with an ) and then makes use of the ast library (see the documentation) to turn the strings with literal_eval into actual tuples and append them to a new list. Subsequently, it applies sorted as you proposed in your question.

Upvotes: 4

Related Questions