小编Leo*_*rao的帖子

更改namedtuples列表的值

我有一个命名的命名元组列表,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)

python tuples list python-3.x

28
推荐指数
2
解决办法
3万
查看次数

标签 统计

list ×1

python ×1

python-3.x ×1

tuples ×1