diff options
Diffstat (limited to 'natsort')
-rw-r--r-- | natsort/natsort.py | 13 | ||||
-rw-r--r-- | natsort/ns_enum.py | 9 |
2 files changed, 21 insertions, 1 deletions
diff --git a/natsort/natsort.py b/natsort/natsort.py index ea83e48..2325443 100644 --- a/natsort/natsort.py +++ b/natsort/natsort.py @@ -288,6 +288,8 @@ def natsorted( ['num2', 'num3', 'num5'] """ + if alg & ns.PRESORT: + seq = sorted(seq, reverse=reverse, key=str) return sorted(seq, reverse=reverse, key=natsort_keygen(key, alg)) @@ -477,6 +479,8 @@ def index_natsorted( # Pair the index and sequence together, then sort by element index_seq_pair = [(x, y) for x, y in enumerate(seq)] + if alg & ns.PRESORT: + index_seq_pair.sort(reverse=reverse, key=lambda x: str(itemgetter(1)(x))) index_seq_pair.sort(reverse=reverse, key=natsort_keygen(newkey, alg)) return [x for x, _ in index_seq_pair] @@ -768,6 +772,7 @@ def os_sorted( seq: Iterable[T], key: Optional[Callable[[T], NatsortInType]] = None, reverse: bool = False, + presort: bool = False, ) -> List[T]: """ Sort elements in the same order as your operating system's file browser @@ -810,6 +815,10 @@ def os_sorted( Return the list in reversed sorted order. The default is `False`. + presort : {{True, False}}, optional + Equivalent to adding ``ns.PRESORT``, see :class:`ns` for + documentation. The default is `False`. + Returns ------- out : list @@ -825,4 +834,6 @@ def os_sorted( This will implicitly coerce all inputs to str before collating. """ - return sorted(seq, key=os_sort_keygen(key), reverse=reverse) + if presort: + seq = sorted(seq, reverse=reverse, key=str) + return sorted(seq, reverse=reverse, key=os_sort_keygen(key)) diff --git a/natsort/ns_enum.py b/natsort/ns_enum.py index c147909..02f970f 100644 --- a/natsort/ns_enum.py +++ b/natsort/ns_enum.py @@ -114,6 +114,14 @@ class ns(enum.IntEnum): # noqa: N801 treat these as +Infinity and place them after all the other numbers. By default, an NaN be treated as -Infinity and be placed first. Note that this ``None`` is treated like NaN internally. + PRESORT, PS + Sort the input as strings before sorting with the `nasort` + algorithm. This can help eliminate inconsistent sorting in cases + where two different strings represent the same number. For example, + "a1" and "a01" both are internally represented as ("a", "1), so + without `PRESORT` the order of these two values would depend on + the order they appeared in the input (because Python's `sorted` + is a stable sorting algorithm). Notes ----- @@ -143,6 +151,7 @@ class ns(enum.IntEnum): # noqa: N801 NANLAST = NL = 1 << next(_counter) COMPATIBILITYNORMALIZE = CN = 1 << next(_counter) NUMAFTER = NA = 1 << next(_counter) + PRESORT = PS = 1 << next(_counter) # Following were previously options but are now defaults. DEFAULT = 0 |