我有一个名为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'
我知道我不能在namedtuple中设置字段。如何更新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
有人能告诉我为什么会这样吗?
这看起来像是Python的数据分析库pandas的任务。做这种事真的很容易:
现在,这难道不比用
namedtuple
s工作要好得多吗?命名元组是不可变的,因此不能对其进行操作。
正确的做法:
如果您想要可变的东西,可以使用^{} 。
PS:如果没有安装,则可能需要
pip install recordtype
。糟糕的做法:
您还可以继续使用} 方法。
namedtuple
和^{在Python>;=3.7中,可以将dataclassdecorator与新的变量注释功能一起使用,以生成可变记录类型:
输出:
相关问题 更多 >
编程相关推荐