If you want to sort the List in python, you can easily sort it by using the sort () function as shown below.
>>> l = ['B', 'C', 'A']
>>> l.sort()
>>> print l
['A', 'B', 'C']
However, if you sort the file list containing dots such as .file
, the files containing dots will be lined up first as shown below.
>>> files = ['file01', 'file02', '.file04', 'file03']
>>> files.sort()
>>> print files
['.file04', 'file01', 'file02', 'file03']
For example, if you want to sort by the part that does not contain dots like the output of the ls command, you can do it by using a lambda expression as follows.
>>> files = ['file01', 'file02', '.file04', 'file03']
>>> sortKey = lambda f: f if not f.startswith('.') else f[1:]
>>> files.sort(key=sortKey)
>>> print files
['file01', 'file02', 'file03', '.file04']
The sortKey specifies how to generate a key for sorting.
Specifically, the sort target is passed as f
, and if there is a dot at the beginning off.startswith ('.')
, The second character is cut out and used as the key.
For example, you can sort the list by file size by doing the following:
>>> import os
>>> files = ['file01', 'file02', '.file04', 'file03']
>>> sortKey = lambda f: os.state(f).st_size
>>> files.sort(key=sortKey)
Recommended Posts