1

I can do a natural sort on a simple list or I can do a normal sort on a specific key in a complex list. I need to do a natural sort on a key in a complex list.

Given this program:

import re

def atof(text):
    try:
        retval = float(text)
    except ValueError:
        retval = text
    return retval

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    float regex comes from https://stackoverflow.com/a/12643073/190597
    '''
    return [ atof(c) for c in re.split(r'[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)', text) ]

alist=[
    "something1",
    "something2",
    "something10.0",
    "something1.25",
    "something1.105"]

alist.sort(key=natural_keys)
print("alist:")
for i in alist: print(i)

from operator import itemgetter

blist=[
    ['a', "something1"],
    ['b', "something2"],
    ['c', "something10.0"],
    ['d', "something1.25"],
    ['e', "something1.105"]]

blist.sort(key=itemgetter(1))
print("\nblist:")
for i in blist: print(i[1])

I get these results:

alist:
something1
something1.105
something1.25
something2
something10.0

blist:
something1
something1.105
something1.25
something10.0
something2

How can I get blist to sort the same as alist?

benvc
  • 14,448
  • 4
  • 33
  • 54
rebelxt
  • 35
  • 6

1 Answers1

1

You could use a lambda instead of itemgetter.

blist.sort(key=lambda x: natural_keys(x[1]))
benvc
  • 14,448
  • 4
  • 33
  • 54