Home > Back-end >  How to sort the contents of a list?
How to sort the contents of a list?

Time:02-05

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!

CodePudding user response:

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]))
]
  •  Tags:  
  • Related