Answer the question
In order to leave comments, you need to log in
How to parse and sort filenames?
The input data is a list of names always in the format "file675.txt" there are many of them. When you try to sort, of course, you get something like:
file1.txt
file100.txt
file2.txt
How can I fix this and how can I parse the names and sort the list correctly for further output?
Answer the question
In order to leave comments, you need to log in
a = ['file1.txt', 'file10.txt', 'file2.txt']
print(sorted(a, key=lambda x: int(x[4:-4])))
it is necessary for each name to make a certain correspondence with the number that is embedded in it.
Create a list of these matches and sort by number.
If you quickly throw it, then something like this will come out:
names = ['file1.txt',
'file100.txt',
'file2.txt']
new_list = []
for name in names:
number = int(name.replace('file', '').replace('.txt', ''))
new_list.append((name, number))
sorted_files = [element[0] for element in sorted(new_list, key=lambda x: x[1])]
print(sorted_files) # ['file1.txt', 'file2.txt', 'file100.txt']
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question