Changing values of a list of namedtuples

后端 未结 3 1775
孤城傲影
孤城傲影 2020-12-28 12:31

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 trie

3条回答
  •  旧时难觅i
    2020-12-28 12:48

    Named tuples are immutable, so you cannot manipulate them.

    Right way of doing it:

    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: You may need to pip install recordtype if you don't have it installed.

    Bad way of doing it:

    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)
    

提交回复
热议问题