我有一个命名的命名元组列表,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)
Run Code Online (Sandbox Code Playgroud)
但我一直在:
Traceback (most recent call last):
print(item.price)
AttributeError: 'float' object has no attribute 'price'
Run Code Online (Sandbox Code Playgroud)
我知道我不能在namedtuple中设置字段.我该如何进行更新price
?
我试着把它变成一个函数:
def restaurant_change_price(rest, newprice):
rest.price = rest._replace(price = rest.price + newprice)
return …
Run Code Online (Sandbox Code Playgroud)