3

I have a list of strings which represent tuples, like so:

['(q2,0)', '(q3,0)', '(q0,0)', '(q1,0)', '(q4,0)']

Is there any way to sort it by accessing the numbers after each q, so that the list looks like this:

[ '(q0,0)', '(q1,0)', '(q2,0)', '(q3,0)', '(q4,0)']

It would be easy if these were integers, however I need to keep the string format as they are now...

Zero Piraeus
  • 52,181
  • 26
  • 146
  • 158
nanachan
  • 941
  • 1
  • 14
  • 24
  • 1
    Not a dupe. Regardless of title, this isn't a list of tuples, it's a list of strings that need to be tuple-fied. Having said that, @nanachan if you ask how to split a string list into a tuple list in python, then check out the the dupe link, you should get sorted. – mcalex Mar 07 '17 at 18:57

3 Answers3

4

You can sort based upon a key which you define:

def my_key(value):
    return int(value.strip('()').split(',')[0][1:])

Usage:

>>> values = ['(q2,0)', '(q3,0)', '(q0,0)', '(q1,0)', '(q4,0)']
>>> values.sort(key=my_key)
['(q0,0)', '(q1,0)', '(q2,0)', '(q3,0)', '(q4,0)']
Peter Wood
  • 22,682
  • 5
  • 57
  • 94
0

You can split the string at the first "," using partition then strip "(q" customize the sort using by supplying a "key" function

lst = ['(q12,0)', '(q3,0)', '(q0,0)', '(q1,0)', '(q4,0)']    
sorted(lst, key=lambda item: int(item.partition(',')[0].strip('(q')))
# '(q0,0)', '(q1,0)', '(q3,0)', '(q4,0)', '(q12,0)']
styvane
  • 55,207
  • 16
  • 142
  • 150
0
lt = ['(q2,0)', '(q3,0)', '(q0,0)', '(q1,0)', '(q4,0)']
lt.sort(key=lambda st : int(st[2]) )
print(lt)

result

['(q0,0)', '(q1,0)', '(q2,0)', '(q3,0)', '(q4,0)']

#st = '(q2,0)'
#st[2] = '2'
#int(st[2]) = 2
Fuji Komalan
  • 1,851
  • 12
  • 24