Skip to content
Advertisement

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?

Or should I use a sorting algorithm with filename?

Any help would be appreciated, thank you!

Advertisement

Answer

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]))
]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement