Nik
Nik

Reputation: 129

Iterate through 2d list and select range from co-ordinates in Python

gridsize=5

m= [[0 for i in range(gridsize)] for i in range(gridsize)]

[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

How could I iterate through the 2D list, given the range of co-ordinates and change their values?

Example: Co-ordinates from position (0,0) to (0,3)

enter image description here

In this instance: m[0][0], m[0][1], m[0][2] and m[0][3] need to be changed.

Example 2: Co-ordinates (2,2) to (2,4)

enter image description here

In this instance: m[2][2], m[2][3] and m[2][4] need to be changed.

Upvotes: 1

Views: 1713

Answers (1)

bakkal
bakkal

Reputation: 55448

Like others have said it's just a list of lists

So you can index it with m[i][j]

But you want a range on the internal list, so you can slice it with m[i][j:k]

>>> m = [[1, 2, 3, 4, 5],
...  [0, 0, 0, 0, 0],
...  [0, 0, 0, 0, 0],
...  [0, 0, 0, 0, 0],
...  [0, 0, 0, 0, 0]]
>>> m[0]
[1, 2, 3, 4, 5]
>>> m[0][0:4]
[1, 2, 3, 4]

To mutate your list, just do

>>> m[0][0:4] = ['a', 'b', 'c', 'd']
>>> m
[['a', 'b', 'c', 'd', 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Your second example

In this instance: m[2][2], m[2][3] and m[2][4] need to be changed.

This is on different than the first example above, because it spans a single row

m[2][2:5] = [1,1,1]

For more advanced matrix/array manipulation try numpy

If the range spans more than 1 row, I suggest you use the numpy library, because it's got easy flattening

>>> m = np.zeros(shape=(5,5))
>>> m
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
>>> f = m.flatten()
>>> f
array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> f[4:7]
array([ 0.,  0.,  0.])
>>> f[4:7] = [1, 1, 1]
>>> f
array([ 0.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
>>> f.shape = 5,5
>>> f
array([[ 0.,  0.,  0.,  0.,  1.],
       [ 1.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])

Upvotes: 3

Related Questions