To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

Commit dee59fb7 authored by vermeul's avatar vermeul
Browse files

even better example with file names

parent 97cb5819
......@@ -38,7 +38,7 @@ print(string[:1].upper() + string[1:])
```
20_Ms_229_7.xml
20_Ms_229_37.xml~
20_Ms_229_37.xml
20_Ms_229_6.xml
20_Ms_229_29.xml
20_Ms_229_15.xml
......@@ -84,33 +84,50 @@ for root, dirs, files in os.walk('.'):
## Sorting: the `sorted` function
**Input** is a similar list of files as above, but this time we would like to apply a two-dimensional sort:
**Input** the list of files, but this time we would like to apply a two-dimensional sort:
1. sort by length of filename, longest filenames first
2. sort by the lowercase of the filename
1. sort by the first two digits, e.g. `20` in `20_Ms_229_7.xml`
2. sort by the last digit, e.g. `15` in `20_Ms_229_15.xml` in descending order
**define the sort functions**
```python
def sort_by_length(filename):
return len(filename)
import re
def sort_by_name(filename):
return filename.lower()
def sort_by_first_number(filename):
match = re.search(r'^(\d+)', filename)
if match:
return int(match.groups()[0])
def sort_by_last_number(filename):
match = re.search(r'_(\d+)\.xml', filename)
if match:
return int(match.groups()[0])
```
**Note:** when doing string comparison, we just return the string (or `string.lower()` for case-insensitive sort). Because we want to compare numbers, we need to apply the `int()` function to enforce number comparison.
**apply the sort functions using `sorted`**
```python
filenames = []
for root, dirs, files in os.walk('..'):
filenames += files
sorted(
sorted(filenames, key=sort_by_name, reverse=False),
key=sort_by_length,
reverse=True
sorted_filenames = sorted(
sorted(
filenames,
key=sort_by_last_number,
reverse=True
),
key=sort_by_first_number
)
# sorted_filenames
['10_Ms_229_29.xml',
'10_Ms_229_15.xml',
'20_Ms_229_37.xml',
'20_Ms_229_7.xml',
'20_Ms_229_6.xml',
...
]
```
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment