所以我对Python很新,并且因为我的入门级CS课程而遇到问题。问题是创建一个列表,其中包含2000年之前创建的所有标题以及2000年之后创建的所有标题。这是我到目前为止所拥有的:
from collections import namedtuple
Book = namedtuple("Book", "author title genre year price instock")
book_1 = Book("Bob", "Harry Potter", "Fantasy", 2000, 6.00, 1000)
book_2 = Book("Martha", "Hunger Games", "Psychological", 1998, 10.00, 2000)
book_3 = Book("Sam", "The Quest", "Adventure", 2010, 8.00, 5000)
book_4 = Book("Damien", "Pokemon", "Sci-Fi", 1990, 12.00, 10000)
book_5 = Book("Voldemort", "Maze Runner", "Adventure", 2015, 10.00, 50)
book_6 = Book("Anonymous", "Horror Stories Before Bed", "Horror", 2017, 18.00,0)
book_store_inventory = [book_1, book_2, book_3, book_4, book_5, book_6]
before_2000 = []
after_2000 = []
for i in book_store_inventory:
if book_store_inventory[i].year <= 2000:
before_2000.append(i.title)
else:
after_2000.append(i.title)
从这一点开始,我应该改变什么?我不断收到错误消息,说列表索引必须是整数或切片,而不是Book。谢谢!
答案 0 :(得分:2)
你不需要索引:
for book in book_store_inventory:
if book.year <= 2000:
before_2000.append(book.title)
else:
after_2000.append(book.title)
答案 1 :(得分:1)
before_2000 = [i.title for i in book_store_inventory if i.year <= 2000]
after_2000 = [i.title for i in book_store_inventory if i.year > 2000]
答案 2 :(得分:0)
由于您有这么多书籍对象,因此创建一个新类来存储书籍并创建property
装饰器以根据特定条件访问库数据可能是有意义的:
class Library:
def __init__(self, books):
self.books = books
@property
def before_2000(self):
return [i for i in self.books if i.year <= 2000]
@property
def after_2000(self):
return [i for i in self.books if i.year > 2000]
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, ', '.join(i.title for i in self.books))
book_store_inventory = [book_1, book_2, book_3, book_4, book_5, book_6]
library = Library(book_store_inventory)
print(library.before_2000)
print(library.after_2000)
print(library)
输出:
[Book(author='Bob', title='Harry Potter', genre='Fantasy', year=2000, price=6.0, instock=1000), Book(author='Martha', title='Hunger Games', genre='Psychological', year=1998, price=10.0, instock=2000), Book(author='Damien', title='Pokemon', genre='Sci-Fi', year=1990, price=12.0, instock=10000)]
[Book(author='Sam', title='The Quest', genre='Adventure', year=2010, price=8.0, instock=5000), Book(author='Voldemort', title='Maze Runner', genre='Adventure', year=2015, price=10.0, instock=50), Book(author='Anonymous', title='Horror Stories Before Bed', genre='Horror', year=2017, price=18.0, instock=0)]
Library(Harry Potter, Hunger Games, The Quest, Pokemon, Maze Runner, Horror Stories Before Bed)