-1

I've been having some issues with some code lately and thought I'd share with this amazing community!

I have a list of strings, that are also string-based lists, delimited by a special character ('~'). For example..

list1 = [
'0~A~Sometext',
'56~B~Sometext',
'3~A~Sometext',
'875~G~Sometext',
'54~V~Sometext',
'3~D~Sometext',
'20~S~Sometext',
'7~R~Sometext'
]

I would like to sort this list based off the first element in the string (0,56,3,875,etc...)

When I try to implement my own sorting algorithm or use Python's sort, it doesn't output the correct order.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

3

You can use a custom function for the sorting, by passing it as the key argument for the sort() method:

list1 = [
    '0~A~Sometext',
    '56~B~Sometext',
    '3~A~Sometext',
    '875~G~Sometext',
    '54~V~Sometext',
    '3~D~Sometext',
    '20~S~Sometext',
    '7~R~Sometext'
]
list1.sort(key=lambda x: int(x.split('~')[0]))
print(list1)

This will take every element:

  1. Split it around the ~, so that '0~A~Sometext' becomes ['0', 'A', 'Sometext']
  2. Take the first element from that list
  3. Make it an integer.

And compare all of those integers to sort the list.

Output:

['0~A~Sometext', '3~A~Sometext', '3~D~Sometext', '7~R~Sometext', '20~S~Sometext', '54~V~Sometext', '56~B~Sometext', '875~G~Sometext']
ruohola
  • 21,987
  • 6
  • 62
  • 97
2

You can define your own sort key and specify it in the sort method.

e.g.

def sort_key(input):
    return int(input.split('~')[0])

list1.sort(key=sort_key)
WhatAmIDoing
  • 198
  • 1
  • 1
  • 6