改变一个命名元组列表的值
改变一个命名元组列表的值
我有一个名为Books
的命名元组列表,并且试图将price
字段增加20%,这确实改变了Books
的值。我尝试过以下方法:
from collections import namedtuple Book = namedtuple('Book', 'author title genre year price instock') BSI = [ 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 item in BSI: item = item.price*1.10 print(item.price)
但是我一直得到:
Traceback (most recent call last): print(item.price) AttributeError: 'float' object has no attribute 'price'
我知道我不能设置命名元组中的字段。我该如何更新price
?
我试图将其变成一个函数:
def restaurant_change_price(rest, newprice): rest.price = rest._replace(price = rest.price + newprice) return rest.price print(restaurant_change_price(Restaurant("Taillevent", "French", "343-3434", "Escargots", 24.50), 25))
但是我得到一个replace错误:
rest.price = rest._replace(price = rest.price + newprice) AttributeError: can't set attribute
有人可以告诉我为什么会发生这种情况吗?