从lis返回大字符串表示

2024-09-29 19:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它获取一个图书列表,并返回每本图书的一个大字符串,后跟一个换行符。你知道吗

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

Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)

我做了以下功能:

def Booklist_display(dlist):
    for item in dlist:
        return '{name} {price} {stock}'.format(name=item.name, price=item.price, stock=item.instock)

但它只印第一本书,不印第二本书。你知道吗

 Suzane Collins 6.96 20

有人能帮我理解我的代码是否正确,为什么我的函数只打印第一部分?我似乎不能确定逻辑。你知道吗


Tags: 函数字符串name列表stockitemnamedtupleprice
2条回答

在这个for循环中:

for item in dlist:
    return '{name} {price} {stock}'.format(name=item.name, price=item.price, stock=item.instock)

当循环在第一个对象上迭代时,函数退出(因为return)。你知道吗

将结果存储在列表中,稍后返回:

strlist = []
for item in dlist:
    strlist.append('{name} {price} {stock}'.format(name=item.name, price=item.price, stock=item.instock))
return '\n'.join(strlist)

您可以将join与列表一起使用。你知道吗

from collections import named tuple

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

books = [Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20),
         Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]

def Booklist_display(dlist):
    return '\n'.join(['{title} {price} {stock}'
                      .format(title=item.title, price=item.price, stock=item.instock)
                      for item in dlist])

>>> Booklist_display(books)
"The Hunger Games 6.96 20\nHarry Potter and the Sorcerer's Stone 4.78 12"

相关问题 更多 >

    热门问题