Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort the contents of a list?

I have the following list:

filenames=["SecretOfChimneys_1925.txt",
        "DeathInTheClouds_1935.txt",
        "SparklingCyanide_1945.txt",
        "HickoryDickoryDock_1955.txt",
        "AtBertramsHotel_1965.txt",
        "Curtain_1975.txt"]
books=[]
for filename in filenames:
    with open(filename) as fin:
        text=fin.read()
        books.append(text)

I need to make a list of book titles ordered by year, with the underscore character and the year removed. For example, the first book title should be "SecretOfChimneys". Call your list booktitles.

Is there a way to use the fact that titles are already sorted by year in books and just select the tiles from that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Or should I use a sorting algorithm with filename?

Any help would be appreciated, thank you!

>Solution :

You can use a lambda as the key when sorting. Then use a list comprehension to extract just the title from the sorted list.

booktitles = [f.split('_')[0] for f in 
    sorted(filenames, key=lambda x: int(x.split('_')[1].split('.')[0]))
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading