1.what could i have done differently or better in this?
2.how can one link the items in one list to another so that no matter whats sorted(title or author, they still remain together??
books=[]
n = int(input("Total number of books "))
while True:
for i in range(1, n 1):
book = (input("the name of the book ")).capitalize()
books.append(book)
break
books.sort()
print(books)
authors=[]
while True:
for i in range(len(books)):
author = (input("Enter the author bookwise ")).capitalize()
author.capitalize()
authors.append(author)
break
print(authors)
print("HERE ARE YOUR BOOKS")
for i in range(len(books)):
print(authors[i], "-", books[i])
CodePudding user response:
You don't need the 'while True' loop, you can just use the for loop.
In the for loop, you can just write:
for i in range(n): ...
You can use a dictionary to match between the book title and the author
CodePudding user response:
Zipping lists
To handle book and author together, use a list of pairs instead of a pair of lists. Builtin function zip
makes it easy to convert a pair of lists into a list of pairs and vice-versa.
from operator import itemgetter
titles = ['There is no antimemetics division', 'A fire upon the deep', 'Ilium']
authors = ['Sam Hughes', 'Vernor Vinge', 'Dan Simmons']
books = list(zip(titles, authors))
print( sorted(books, key=itemgetter(0)) ) # sorted by title
# [('A fire upon the deep', 'Vernor Vinge'), ('Ilium', 'Dan Simmons'), ('There is no antimemetics division', 'Sam Hughes')]
print( sorted(books, key=itemgetter(1)) ) # sorted by author
# [('Ilium', 'Dan Simmons'), ('There is no antimemetics division', 'Sam Hughes'), ('A fire upon the deep', 'Vernor Vinge')]
Pretty formatting
max_author_len = max(len(a) for a in authors)
max_title_len = max(len(t) for t in titles)
books.sort(key=itemgetter(1))
for title, author in books:
print('{author:{width}s} - {title}'.format(width=max_author_len, author=author, title=title))
# Dan Simmons - Ilium
# Sam Hughes - There is no antimemetics division
# Vernor Vinge - A fire upon the deep
books.sort(key=itemgetter(0))
for title, author in books:
print('{title:{width}s} - {author}'.format(width=max_title_len, author=author, title=title))
# A fire upon the deep - Vernor Vinge
# Ilium - Dan Simmons
# There is no antimemetics division - Sam Hughes