Updating multi-dimensional tuples using python list comprehension

  • Two-dimensional tuple

    Below sample has a tuple that contains multiple book details. Each of these is stored as a tuple with book id, book name and the price. We will try adding a new field tax to each item and calculate it as 5% of price. Also add this amount to the existing price column.

    Copied
    from datetime import datetime
    
    books = (
        (1, 'Book 1', 100.50),
        (2, 'Book 2', 80.75),
        (3, 'Book 3', 50.00)
    )
    
    #Find new price after adding tax
    newPrice = ( ( b[0], b[1], round(float(b[2] / 10),2), round(b[2] + float(b[2] / 20),2) )  for b in books)
    print(tuple(newPrice))
    
    Output:
    (
    	(1, 'Book 1', 10.05, 105.53),
    	(2, 'Book 2', 8.07, 84.79),
    	(3, 'Book 3', 5.0, 52.5)
    )
    
  • Three-dimensional tuple

    This sample has an additional level, with average prices across locations.
    See below how we can update a tuple with three levels.

    Copied
    from datetime import datetime
    
    books = (
        (1, 'Book 1', 
            (100, 90, 80)),
        (2, 'Book 2', 
            (75, 70, 80)),
        (3, 'Book 3', 
            (50, 55, 55)),
    )
    
    #Find average price
    newPrice = ( ( b[0], b[1], round((b[2][0] + b[2][1] + b[2][2])/3) )  for b in books)
    print(tuple(newPrice))
    
    #Find average price and also keep third level
    newPrice = ( ( b[0], b[1], round((b[2][0] + b[2][1] + b[2][2])/3), b[2] )  for b in books)
    print(tuple(newPrice))
    
    Outputs:
    (
    	(1, 'Book 1', 90),
    	(2, 'Book 2', 75),
    	(3, 'Book 3', 53)
    )
    
    (
    	(1, 'Book 1', 90, (100, 90, 80)),
    	(2, 'Book 2', 75, (75, 70, 80)),
    	(3, 'Book 3', 53, (50, 55, 55))
    )
    
Absolute Code Works - Python Topics