命名元组是 不可变的 ,因此您无法操作它们。
正确的做法:
如果您想要 可变的 东西,可以使用
recordtype。
from recordtype import recordtypeBook = recordtype('Book', 'author title genre year price instock')books = [ Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20), Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]for book in books: book.price *= 1.1 print(book.price)PS:
pip install recordtype如果您没有安装它,则可能需要。
坏方法:
您还可以继续使用
namedtuple,使用的
_replace()方法。
from collections import namedtupleBook = namedtuple('Book', 'author title genre year price instock')books = [ Book('Suzane Collins','The Hunger Games', 'Fiction', 2008, 6.96, 20), Book('J.K. Rowling', "Harry Potter and the Sorcerer's Stone", 'Fantasy', 1997, 4.78, 12)]for i in range(len(books)): books[i] = books[i]._replace(price = books[i].price*1.1) print(books[i].price)


