sorting strings numerically while dealing with missing values
ian.g.kelly at gmail.com
Wed Dec 28 15:46:48 EST 2016
On Wed, Dec 28, 2016 at 2:43 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> On Wed, Dec 28, 2016 at 2:14 PM, Larry Martell <larry.martell at gmail.com> wrote:
>> I have a list containing a list of strings that I want to sort
>> numerically by one of the fields. I am doing this:
>> sorted(rows, key=float(itemgetter(sortby)))
> I'm guessing that you left out a lambda here since the key argument
> takes a function.
>> Which works fine as long as all the sort keys convert to a float.
>> Problem is that some are blank or None and those throw an exception.
>> How can I handle that case and still sort? I'd want the blank or None
>> fields to come out either at the beginning or end of the sorted list
>> (not sure what the customer wants for this yet).
> def sort_key(sortby, none_first=False):
> def key(row):
> value = float(row[sortby])
> except ValueError:
> value = None
> return ((value is None) != none_first, value)
> return key
> sorted(rows, key=sort_key(4, none_first=True))
Actually that doesn't quite work because None < None is unorderable in
Python 3. Maybe replace the inner return with:
return ((value is None) != none_first, value or 0.0)
More information about the Python-list