简体   繁体   中英

Writing a sequence of statements to print a certain category in a namedtuple

Write a sequence of statements that prints the title of each book in BSI, one per line.

from collections import namedtuple
Book = namedtuple('Book', 'author title genre year price instock')

BSI = [
    Book('Tyler Hawkin','ABC','education', 2009, 20.00, 75), 
    Book('Miss Hanigan','Jannie','adventure', 1900, 26.00, 51),
    Book('Leila Star','My first crush','comedy', 2013, 8.89, 11), 
    Book('John Green', 'Fault in our Stars', 'romance' ,2006, 17.00, 0),
    Book('Shakespeare', 'Romeo', 'Drama', 1610, 5.00, 99),
    Book('Janett Smith','How to be Young Again','life', 1995, 13.00, 3) ]

def book_title(book:"Book") -> str:
    return book.title

With the code above, I can call any book title, but how would I alter this code so that it prints all the titles one line each?

since list of tuples is iterable you can loop over the named tuple

for book in BSI:
    print(book.title)

ABC
Jannie
My first crush
Fault in our Stars
Romeo
How to be Young Again

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM