python – 更改namedtuples列表的值

我有一个名为Books的名单元素列表,我试图将价格字段提高20%,这确实会改变图书的价值.我试着这样做:

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中设置字段.我该如何更新价格?

我试着把它变成一个函数:

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))

但我得到一个错误,替换说:

 rest.price = rest._replace(price = rest.price + newprice)
 AttributeError: can't set attribute

有人能告诉我为什么会这样吗?

解决方法:

命名元组是不可变的,因此您无法操纵它们.

正确的做法:

如果你想要一些可变的东西,你可以使用recordtype.

from recordtype import recordtype

Book = 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.

糟糕的做法:

您也可以使用_replace()方法继续使用namedtuple.

from collections import namedtuple

Book = 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)
上一篇:python – 为什么解压缩元组会导致语法错误?


下一篇:元组对,使用python找到最小值