【问题标题】:How to get a sorted list of namedtuples' attributes如何获取命名元组属性的排序列表
【发布时间】:2016-04-13 20:16:24
【问题描述】:

我完全不知道为什么我不断收到错误。我正在尝试使用sorted() 打印按字母顺序列出的书籍的标题。

我不断收到此错误:

sorted(BSI, key=list(Book))
TypeError: 'type' object is not iterable

那就是代码

from collections import namedtuple

Book = namedtuple('Book', 'author title genre year price instock')
BSI = [Book("J.K. Rowling", "Harry Potter", "Fantasy", "2005", 12.00, "34"),
       Book("Dr. Seuss", "Green Eggs and Ham", "Children's", "2000", 8.00, "12"),
       Book("Margaret Mitchell", "Gone with the Wind", "Fiction", "1980", 9.00, "30"),
       Book("John Green", "The Fault in our Stars", "Fiction", "2010", 13.00, "23"),
       Book("Stephanie Meyer", "Twilight", "Fantasy", "2008", 15.00, "8"),
       Book("Suzanne Collins", "The Hunger Games", "Fantasy", "2005", 17.00, "18")]

for x in BSI:
    print(x.title)

y = BSI
for x in BSI:
    sorted(BSI, key=list(Book))

【问题讨论】:

标签: python sorting attributes namedtuple


【解决方案1】:

问题在于list(Book)。书是一种类型。以下可能是您想要的。

from collections import namedtuple

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

BSI = [
    Book ("J.K. Rowling", "Harry Potter", "Fantasy", "2005", 12.00 ,     "34"),
    Book ("Dr. Seuss", "Green Eggs and Ham", "Children's", "2000", 8.00 , "12"),
    Book ("Margaret Mitchell", "Gone with the Wind", "Fiction", "1980", 9.00, "30"),
    Book ("John Green", "The Fault in our Stars", "Fiction", "2010", 13.00, "23"),
    Book ("Stephanie Meyer", "Twilight", "Fantasy", "2008", 15.00, "8"),
    Book ("Suzanne Collins", "The Hunger Games", "Fantasy", "2005", 17.00, "18"),
    ]

for x in BSI:
    print (x.title)
print()
for x in sorted(BSI, key=lambda x: x.title):
    print(x.title)

如果您真的认为您可能有重复的标题,您可以详细说明密钥。

【讨论】:

    猜你喜欢
    • 2015-03-10
    • 2015-09-12
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多