Numerically sort a list of strings.
(l)
| 84 | |
| 85 | |
| 86 | def numericSorted(l): |
| 87 | """Numerically sort a list of strings.""" |
| 88 | |
| 89 | # pattern to split name into numeric and non-numeric parts |
| 90 | splitter_pattern = re.compile('([0-9]+|[^0-9]+)') |
| 91 | |
| 92 | def keyfunc(name): |
| 93 | """Sorting key for numeric sorting.""" |
| 94 | split_name = re.findall(splitter_pattern, name) |
| 95 | # one-liner to convert numeric parts into integers |
| 96 | split_name = list(map(lambda x: int(x) if x.isdigit() else x, split_name)) |
| 97 | # ensure that list begins with a string to avoid string<->int compare |
| 98 | if split_name and isinstance(split_name[0], int): |
| 99 | split_name.insert(0, '') |
| 100 | return split_name |
| 101 | |
| 102 | # return the numerically sorted list |
| 103 | return sorted(l, key=keyfunc) |
| 104 | |
| 105 | |
| 106 | # ----------------------------------------------------------------------------- |
no test coverage detected