0

i have a list

a1 = ['1', '5-10', '12', '18', '23', '100-110', '16-17', '20']

i want this list of elements in increasing order like

a1 = ['1','5-10','12','16-17','18','20','23','100-110']

please anyone help me to arrange this

case = ['1', '5-10', '12', '18', '23', '100-110', '16-17', '20']
case1 = [i.split('-', 1)[0] for i in case]
case1 = [int(x) for x in case1]

case1.sort()

after print the case1 output is

[1, 5, 12, 16, 18, 20, 23 ,100]

but i want the output is like

[1, 5-10, 12, 16-17, 18, 20, 23, 100-110]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Can you please update the question with the code that you've already tried? Also please add the expected output for situations where ranges have intersection or numbers are inside a range. – Mazdak Apr 30 '18 at 08:02
  • thank u for ur response, i had edited the question please check once – Maddela Tejaswini4029 Apr 30 '18 at 08:11

1 Answers1

0

if you sure that each list element should be either an integer string or a dash-separated string compound by integers, you may try something like this:

a_dict = {int(v.split('-')[0]): v for v in a}
final_a = [a_dict[k] for k in sorted(a_dict)]
print final_a

That returns

['1', '5-10', '12', '16-17', '18', '20', '23', '100-110']

dbrus
  • 79
  • 1
  • 3
  • @MaddelaTejaswini4029 It works fine doesn't mean that it works always and efficiently. – Mazdak Apr 30 '18 at 08:23
  • You could simply use a `key` function in `sorted` function that does all those checks. Also using only the first item or maybe the last item in a range might not produce the expected result. – Mazdak Apr 30 '18 at 08:31