从namedtuple列表中选择标题的麻烦

时间:2013-10-17 05:05:13

标签: python list namedtuple

我想选择书的标题,并按字母顺序列出新的列表

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

for i in BSI:    打印(排序(I.标题))

1 个答案:

答案 0 :(得分:0)

您使用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)]