4.1. natsort_keygen()

natsort.natsort_keygen(key=None, alg=0, **_kwargs)

Generate a key to sort strings and numbers naturally.

Generate a key to sort strings and numbers naturally, not lexicographically. This key is designed for use as the key argument to functions such as the sorted builtin.

The user may customize the generated function with the arguments to natsort_keygen, including an optional key function.

Parameters:
  • key (callable, optional) – A key used to manipulate the input value before parsing for numbers. It is not applied recursively. It should accept a single argument and return a single value.
  • alg (ns enum, optional) – This option is used to control which algorithm natsort uses when sorting. For details into these options, please see the ns class documentation. The default is ns.INT.
Returns:

out – A function that parses input for natural sorting that is suitable for passing as the key argument to functions such as sorted.

Return type:

function

See also

natsorted()

Examples

natsort_keygen is a convenient way to create a custom key to sort lists in-place (for example).:

>>> a = ['num5.10', 'num-3', 'num5.3', 'num2']
>>> a.sort(key=natsort_keygen(alg=ns.REAL))
>>> a
['num-3', 'num2', 'num5.10', 'num5.3']