Reputation: 657
I need to sort a list of strings based on a float value in the middle of the string.
I've seen some answers getting a key keys.sort(key=float)
, but on those answers they have only the float numbers inside the list. In this case I need to convert that piece of the string to float and sort it based on that value. At the end I will need the whole string.
list_of_msg = []
msg1 = "buy.apple<100; 21.15; Jonh>"
msg2 = "buy.apple<100; 20.00; Jane>"
msg3 = "buy.apple<50; 20.10; Anne>"
list_of_msg.append(msg1)
list_of_msg.append(msg2)
list_of_msg.append(msg3)
# sort method goes here
print(list_of_msg)
Expected this to be sorted based on the values 21.15, 20.00, 20.10
['buy.apple<100; 20.00; Jane>', 'buy.apple<50; 20.10; Anne>',
'buy.apple<100; 21.15; Jonh']
Upvotes: 0
Views: 191
Reputation: 26039
Use sorted
/ sort
with key
argument:
sorted(list_of_msg, key=lambda x: float(x.split(';')[1].strip()))
We split elements in original list based on ';'
and take second split which is passed as key
argument.
Upvotes: 3