Chichi - 1 year ago 62
Python Question

# How to assign a column in 2d-array to some repetitive range using Python?

I want to assign column values of 2d array to some repetitive range.

For example, range will be from 1 to 3:

``````[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
``````

I have this code:

``````width, height = 3, 6
array2d = [[0 for x in range(width)] for y in range(height)]

repRange = list(range(1,4)) #it is [1, 2, 3]

j = 0
for i in range(height):
array2d[i][0] = repRange[j]

if j >= len(repRange)-1:
j = 0
j += 1

for row in array2d:
print(row)
``````

Output:

``````[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
[2, 0, 0]
[3, 0, 0]
[2, 0, 0]
``````

It fails. It started good, but in second repetition it failed.

What is wrong with the logic? If there is a more simple and elegant approach, I would be happy if you share it.

The problem with your logic is that when you get to the end of the `repRange` you are setting `j` to 1 instead of 0. That happens because `j += 1` is after the `if` statement; the test in the `if` statement also needs to be adjusted. Here's a repaired version of your code.

``````width, height = 3, 6
array2d = [[0 for x in range(width)] for y in range(height)]

repRange = list(range(1, 4)) #it is [1, 2, 3]

j = 0
for i in range(height):
array2d[i][0] = repRange[j]

j += 1
if j >= len(repRange):
j = 0

for row in array2d:
print(row)
``````

output

``````[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
[1, 0, 0]
[2, 0, 0]
[3, 0, 0]
``````

Here's a more compact version.

``````from itertools import cycle

width, height = 3, 6
repRange = cycle(range(1, 4))
zeroes = [0] * (width - 1)
array2d = [[next(repRange)] + zeroes for y in range(height)]

for row in array2d:
print(row)
``````

And here's another:

``````from itertools import cycle

width, height = 3, 6
zeroes = [0] * (width - 1)
array2d = [[v] + zeroes for _, v in zip(range(height), cycle(range(1, 4)))]

for row in array2d:
print(row)
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download