Home > OS >  Using zip & *, sort the list 'books_borrowed' alphabetically while ensuring that reference
Using zip & *, sort the list 'books_borrowed' alphabetically while ensuring that reference

Time:12-01

new_value= list(zip(books_borrowed,isbn))

book_sorted, isbn_sorted = list(zip(*new_value))

book_sorted= sorted(book_sorted)

print(book_sorted) print(isbn_sorted)

I WANT THE ISBN VALUE TO STICK W THE SORTED BOOK

WHAT SHOULD I DO

CodePudding user response:

you can use the key argument of the sorted function and the operator.itemgetter function from the standard library

import operator


def sort_books(books_borrowed, isbn):
    zipped = zip(books_borrowed, isbn)
    sorted_zipped = sorted(zipped, key=operator.itemgetter(0))
    return list(zip(*sorted_zipped))

>>> sort_books(
...     ["lord of the rings", "Dune", "h2g2"], 
...     ["ltr_isbn", "d_isbn", "h2g2_isbn"]
... )
('Dhune', 'h2g2', 'lord of the rings'), ('d_isbn', 'h2g2_isbn', 'ltr_isbn')

here is some more documentation on how to sort in python

  • Related