0

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.

Awsmike
  • 751
  • 1
  • 7
  • 19

1 Answers1

4

You have to specify a custom function as sort key, which would extract the initial numbers from each string

>>> apples.sort(key=lambda x: int(x.split()[0]))
>>> apples
['2 The Yellow Apples ', '7 The Red Apples ', '15 The Green Apples ', '43 The Blue Apples ', '178 The Purple Apples ']
>>> 

Or using regex

>>> import re
>>> apples.sort(key=lambda x: int(re.findall('\d+', x)[0]))
>>> apples
['2 The Yellow Apples ', '7 The Red Apples ', '15 The Green Apples ', '43 The Blue Apples ', '178 The Purple Apples ']
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • This was exactly what I was looking for, thank you... now out of curiosity, how can I change the sorting from ascending to descending? – Awsmike Jul 13 '18 at 19:51
  • You would pass the additional keyword argument `reverse=True`. See the documentation for the `list.sort` method here: https://docs.python.org/3/tutorial/datastructures.html#more-on-lists – Patrick Haugh Jul 13 '18 at 20:01
  • 1
    Another way would be to simply negate the value: `key=lambda x: -int(x.split()[0])`. – Tom Zych Jul 13 '18 at 21:34