Tuesday, 15 January 2013

sorting - Does Python have a built in function for string natural sort? -



sorting - Does Python have a built in function for string natural sort? -

using python 3.x, have list of strings perform natural alphabetical sort.

natural sort: order files in windows sorted.

for instance, next list naturally sorted (what want):

['elm0', 'elm1', 'elm2', 'elm9', 'elm10', 'elm11', 'elm12', 'elm13']

and here's "sorted" version of above list (what have):

['elm11', 'elm12', 'elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']

i'm looking sort function behaves first one.

there 3rd party library on pypi called natsort (full disclosure, package's author). case, can either of following:

>>> natsort import natsorted, ns >>> x = ['elm11', 'elm12', 'elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] >>> natsorted(x, key=lambda y: y.lower()) ['elm0', 'elm1', 'elm2', 'elm9', 'elm10', 'elm11', 'elm12', 'elm13'] >>> natsorted(x, alg=ns.ignorecase) # or alg=ns.ic ['elm0', 'elm1', 'elm2', 'elm9', 'elm10', 'elm11', 'elm12', 'elm13']

you should note natsort uses general algorithm should work input throw @ it.

if need sorting key instead of sorting function, utilize either of below formulas.

>>> natsort import natsort_keygen, ns >>> l1 = ['elm0', 'elm1', 'elm2', 'elm9', 'elm10', 'elm11', 'elm12', 'elm13'] >>> l2 = l1[:] >>> natsort_key1 = natsort_keygen(key=lambda y: y.lower()) >>> l1.sort(key=natsort_key1) >>> l1 ['elm0', 'elm1', 'elm2', 'elm9', 'elm10', 'elm11', 'elm12', 'elm13'] >>> natsort_key2 = natsort_keygen(alg=ns.ignorecase) >>> l2.sort(key=natsort_key2) >>> l2 ['elm0', 'elm1', 'elm2', 'elm9', 'elm10', 'elm11', 'elm12', 'elm13']

python sorting python-3.x

No comments:

Post a Comment