【问题标题】:returning large string representation from a list从列表中返回大字符串表示
【发布时间】:2015-10-03 22:15:18
【问题描述】:

我有一个函数,它接受书籍列表并返回每本书的一个大字符串,后跟一个换行符。

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

谁能帮我理解我的代码是否正确以及为什么我的函数只打印第一部分?我似乎无法确定逻辑。

【问题讨论】:

  • @YuHao。结果应该是它的打印结果......但它应该打印该列表中的所有元素,而不仅仅是一个。结果应该是一个大字符串,由每本书的字符串表示形式后跟换行符('\n')组成。

标签: python list python-3.x return tuples


【解决方案1】:

在这个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)

【讨论】:

    【解决方案2】:

    您可以将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"
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 2013-12-26
      • 2020-04-21
      相关资源
      最近更新 更多