从名称对列表中选择标题时出现问题

2024-05-15 08:27:53 发布

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

我想选一本书的书名,然后按字母顺序列出一个新的书名

Book = namedtuple('Book', 'author title genre year price instock')
             BSI = [Book('JK Rowling', 'Harry Potter', 'Fiction', 2009, 12.50, 10),
Book('Stephanie Meyer', 'Twilight', 'Fiction', 2007, 9.99, 1),
Book('Walter Isaacson', 'Steve Jobs', 'Technology', 2011, 35.00, 200),
Book('Albert Camus', 'The Stranger', 'Fiction', 1980, 15.99, 62),
Book('Shakespeare', 'Romeo and Juliet', 'Tragedy', 1597, 11.00, 13),
Book('Sake Jager', 'Language Teaching and Language Technology', 'Technology', 1998, 87.00, 27)]

对于BSI中的i: 打印(排序(i.title))


Tags: and顺序title字母namedtupleyearlanguageprice
1条回答
网友
1楼 · 发布于 2024-05-15 08:27:53

你可以使用namedtuple很好。在

您对sorted的使用不正确。您需要通过提供key参数对整个集合进行排序。在

sorted(BSI,key=lambda x:x.title)
Out[39]: 
[Book(author='JK Rowling', title='Harry Potter', genre='Fiction', year=2009, price=12.5, instock=10),
 Book(author='Sake Jager', title='Language Teaching and Language Technology', genre='Technology', year=1998, price=87.0, instock=27),
 Book(author='Shakespeare', title='Romeo and Juliet', genre='Tragedy', year=1597, price=11.0, instock=13),
 Book(author='Walter Isaacson', title='Steve Jobs', genre='Technology', year=2011, price=35.0, instock=200),
 Book(author='Albert Camus', title='The Stranger', genre='Fiction', year=1980, price=15.99, instock=62),
 Book(author='Stephanie Meyer', title='Twilight', genre='Fiction', year=2007, price=9.99, instock=1)]

相关问题 更多 >