Everything in my code is returning what i expect, until i get to the last portion. The sort method is not returning my list in alphabetical order. I keep trying different vectors of corrections, but am brand new to python/coding, and clearly don't have a grasp on what i need to do. Please help. How do i concatenate these strings then print them out in alphabetical order:
Dickens** Hardy** Tolstoy** Twain** Uris**
books = ['War and Peace', 'Huckleberry Finn', 'The Return of the Native', 'A Christmas Carol', 'Exodus']
authors = ['Tolstoy', 'Twain', 'Hardy', 'Dickens' 'Uris']
authorBooks = []
for i in range(len(books)):
authorBooks = [authors[i] ' wrote ' books[i]]
authorBooks = list()
while i < 4:
print(''.join(authorBooks))
break
authorBooks = []
for i in range(len(books)):
authorBooks = [authors[i] ' wrote ' books[i]]
authorBooks = list()
while i < 4:
print(''.join(authorBooks))
break
CodePudding user response:
there's a better way to concatenate one to one mapping lists with same indexes
books = ['War and Peace', 'Huckleberry Finn', 'The Return of the Native', 'A Christmas Carol', 'Exodus']
authors = ['Tolstoy', 'Twain', 'Hardy', 'Dickens', 'Uris']
concatenated = []
for x, y in zip(authors, books):
concatenated.append("{} wrote {}".format(x,y))
concatenated.sort()
print("\n".join(concatenated))
CodePudding user response:
If their is no restriction around using the existing list you can simply add the string to the existing list and avoid creating new list altogether
books = ['War and Peace', 'Huckleberry Finn', 'The Return of the Native', 'A Christmas Carol', 'Exodus']
authors = ['Tolstoy', 'Twain', 'Hardy', 'Dickens', 'Uris']
books = sorted([authors[i] ' wrote ' books[i] for i in range(len(authors))])
print(books)
###
['Dickens wrote A Christmas Carol', 'Hardy wrote The Return of the Native', 'Tolstoy wrote War and Peace', 'Twain wrote Huckleberry Finn', 'Uris wrote Exodus']
CodePudding user response:
Use sorted
from the built-in functions to order them (to reverse the order just pass a further parameter reverse=True
) and zip
to make pairing. I assumed the both lists have the same size, otherwise zip
will automatically drop the last values of the longest one. In the ordering I didn't not distinguish between upper and lower case characters, casefold()
.
books = ['War and Fish', 'War and Peace', 'Huckleberry Finn', 'The Return of the Native', 'A Christmas Carol', 'Exodus']
authors = ['xxx', 'Tolstoy', 'Twain', 'Hardy', 'Dickens' 'Uris']
pairs = list(zip(books, authors))
order_by_books = sorted(pairs, key=lambda pair: pair[0].casefold())
order_by_author = sorted(pairs, key=lambda pair: pair[1].casefold())
print('By books name:')
for book, author in order_by_books:
print(f'{author} wrote "{book}"')
print('By authors:')
for book, author in order_by_author:
print(f'{author} wrote "{book}"')