2D Arrays
A 2D array stores values in rows and columns. You often need the total for just one row or one column, such as one shop's stock of every product, or one product's stock across every shop. To do that, keep one index fixed and let a single loop run over the other index.
| product 0 | product 1 | product 2 | product 3 | |
|---|---|---|---|---|
| shop 0 | 12 | 8 | 15 | 10 |
| shop 1 | 9 | 14 | 7 | 11 |
| shop 2 | 13 | 6 | 12 | 9 |
Shop 1's stock counts are the row stock[1]; the stock counts for product 2 are the column stock[0][2], stock[1][2] and stock[2][2].
To total a row, fix the row index and use a single loop over the column index. The first index never changes, so every value you add comes from that one row, whichever column the loop is currently on.
stock = [[12, 8, 15, 10], [9, 14, 7, 11], [13, 6, 12, 9]]
shop = 1
shop_total = 0
for product in range(len(stock[shop])):
shop_total = shop_total + stock[shop][product]
print("Shop", shop, "total stock:", shop_total)Output:
Shop 1 total stock: 41
If you total several rows one after another, set shop_total back to 0 before each row starts. Otherwise the second row's total also counts the values you added for the first row.
To total a column, fix the column index and loop over the row index instead. The second index stays the same while the first one changes, so you take one value from each row and walk down the column.
The average is the total divided by the number of values you added, so the divisor depends on which way you looped. A row total is divided by the number of columns, len(stock[0]), because you added one value from each column. A column total is divided by the number of rows, len(stock), because you added one value from each row. Using the wrong one still gives a sensible-looking number, so check that the divisor matches the direction of your loop. In the table, each shop's average divides by 4 and each product's average divides by 3.
stock = [[12, 8, 15, 10], [9, 14, 7, 11], [13, 6, 12, 9]]
product = 2
product_total = 0
for shop in range(len(stock)):
product_total = product_total + stock[shop][product]
average = product_total / len(stock)
print("Average stock for product", product, "per shop:", average)Output:
Average stock for product 2 per shop: 11.333333333333334 OCR GCSE Computer Science · 2D Arrays