从命名元组列表中选择标题时出现问题



我想选择书名并按字母顺序创建一个新列表

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.标题))

你用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)]

最新更新