[Tutor] The Python way and two dimensional lists
Phil
phillor9 at gmail.com
Tue Dec 7 02:19:51 EST 2021
On 22/11/21 11:55, Alan Gauld via Tutor wrote:
>
> Also, using python "2D" lists there is no way to
> access the entire column (in your example) you can
> only access a whole row.
>
> You can build a copy of a column easily enough with:
>
> col6 = [row[5] for row in solution]
>
> But if you change any values you need to regenerate
> the copy so it's not exactly efficient.
I've used this idea to simplify a section of my otherwise complex code
to access columns. I've spent the whole day trying to simplify another
area of confusing code, the code is simpler but it doesn't do what I
want and I can see why but I don't know how to proceed.
What I have is a 9 x 9 grid and there are three 3 x 3 boxes per line
which means that I have nine 3 x 3 boxes in total. Each box is accessed
by it's top left coordinates:
box_start = [(0, 0), (0, 3), (0, 6),
(3, 0), (3, 3), (3, 6),
(6, 0), (6, 3), (6, 6)
]
for x, y in box_start:
...
for col in range(x, x + 3):
...
for row in range(y, y + 3):
print(f'self.solution[row][col]
{self.solution[row][col]}')
This works but I know that it's not the correct method and I still find
accessing columns within a 2D array confusing. I only got this working
by trial and error by swapping the x and y coordinates. I think all I've
done is turn the grid onto it's side.
So, by adapting Alan's suggestion I can print the top three boxes as
columns:
for c in range(y, y + 3):
col = [row[c] for row in self.solution[:3]]
print(col)
This does exactly what I want. The question is, how do I use the x
variable to step down to the next row of boxes? The next row starts at 3
instead of 0.
I hope this is less confusing to the reader than it is to me.
--
Regards,
Phil
More information about the Tutor
mailing list