Home > OS >  How to sort a nested list through one of its elements?
How to sort a nested list through one of its elements?

Time:09-28

I have a program to make a bookstore database, and I have used CSV to store my data, through using nested list with each list as an entry for a particular book. The fields are ["Book ID","Title","Genre","Author","Stock"], and in a function to tabulate the data (tabulate module used), I wanted to give the option to sort the data alphabetically using each entry's 2nd element ("Name").

This is my current function :-

def admin_showall():
    print("----------------------------------------\n")
    with open("Book_List.csv","r ") as f:
        all_data = csv.reader(f,delimiter=",")
        next(all_data)
        print("[All Books]\n")
        fields = ["Book ID","Title","Genre","Author","Stock"]
        print(tabulate(all_data,fields))
    print("\nSuccessfully displayed!")
    print("\nFilters to apply:")
    print("   [1] Sort By Name\n   [2] Sort by Genre\n   [3] Sort by Author\n   [4] Sort by Stock")
    ans = input("Enter your choice: ")
    if ans == "1":

It's incomplete, as I can't figure out how to sort the data. Could anyone give any suggestions?

CodePudding user response:

That's pretty easy with

a = [[0, 'Beta', 3], [1, 'Alpha', 11], [7, 'Gamma', 5]]
b = sorted(a, key=lambda x: x[1])
print(b)
# [[1, 'Alpha', 11], [0, 'Beta', 3], [7, 'Gamma', 5]]
  • Related