更改命名元组列表的值 [英] Changing values of a list of namedtuples

查看:101
本文介绍了更改命名元组列表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Books的命名元组列表,并且正在尝试将price字段增加20%,这确实会更改Books的值.我尝试这样做:

I have a list of namedtuples named Books and am trying to increase the price field by 20% which does change the value of Books. I tried to do:

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?

I understand that I cannot set the fields in a namedtuple. How do I go about updating price?

我试图将其变成一个函数:

I tried to make it into a function:

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

有人可以让我知道为什么会这样吗?

Can someone let me know why this is happening?

推荐答案

命名元组是不可变的,因此您无法对其进行操作.

Named tuples are immutable, so you cannot manipulate them.

如果您想要可变,可以使用 recordtype .

If you want something mutable, you can use 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.

PS: You may need to pip install recordtype if you don't have it installed.

您还可以继续将namedtuple _replace() 方法.

You may also keep using namedtuple with using the _replace() method.

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)

这篇关于更改命名元组列表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆