I've read many similar questions, but none of the solutions match the requirements I need which is, using Python 2.6.6 and without installing or using OrderedDict, how can I get my list to sort based on the first numbers in each item?
This is my list:
apples = [ '15 The Green Apples ',
'43 The Blue Apples ',
'2 The Yellow Apples ',
'7 The Red Apples ',
'178 The Purple Apples '
]
apples.sort() gives me:
[ '15 The Green Apples ',
'178 The Purple Apples ',
'2 The Yellow Apples ',
'43 The Blue Apples ',
'7 The Red Apples '
]
What I'd want is:
[ '2 The Yellow Apples ',
'7 The Red Apples ',
'15 The Green Apples ',
'43 The Blue Apples ',
'178 The Purple Apples '
]
I tried converting the list to a dictionary and giving the first numbers 15; 43; 2; 7; 178; but that didn't work. I understand why it's sorting that way, as it's a string, but I can't convert it into an int.
I was thinking maybe using regex, but didn't get very far.
This grabs everything after the first space in the numbers:
[^0-9]
This grabs only the beginning numbers:
[.0-9]
A solution I think would work, but I don't know how to do this, is to match using regex just the numbers and cast that as an int, and sort that way.
EDIT: Possible duplicate question has different acceptable solution, different format, but similar question.