Changing values of a list of namedtuples

后端 未结 3 1774
孤城傲影
孤城傲影 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条回答
  •  轮回少年
    2020-12-28 12:51

    In Python >= 3.7 you can use dataclass decorator with the new variable annotations feature to produce mutable record types:

    from dataclasses import dataclass
    
    
    @dataclass
    class Book:
        author: str
        title: str
        genre: str
        year: int
        price: float
        instock: int
    
    
    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.price *= 1.10
        print(f"New price for '{item.title}' book is {item.price:,.2f}")
    

    Output:

    New price for 'The Hunger Games' book is 7.66
    New price for 'Harry Potter and the Sorcerer's Stone' book is 5.26
    

提交回复
热议问题