I have a 2D array from a geotiff file. See the example array below:
example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 2, 1, 1, 2, 0, 0, 0],
[ 0, 3, 1, 1, 3, 0, 0],
[ 4, 1, 1, 4, 0, 0, 0],
[ 0, 5, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
I am attempting to write a program that will change the first number greater than 1 in each nested list to the 'value + 100'.
With the help of others see the below working code snippet:
for i, sub_list in enumerate(example_array[1:], start= 1):
for j, entry in enumerate(sub_list[1:][1:1], start = 1):
if entry > 1 and j != 1 and j != len(sub_list):
example_array[i][j] += 100
print(example_array)
The above code produces the below incorrect example array where none of the values are changing:
incorrect_example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 2, 1, 1, 2, 0, 0, 0],
[ 0, 3, 1, 1, 3, 0, 0],
[ 4, 1, 1, 4, 0, 0, 0],
[ 0, 5, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
I would like to create the following correct example array
correct_example_array = [[ 0, 1, 1, 0, 0, 0, 0],
[ 102, 1, 1, 2, 0, 0, 0],
[ 0, 103, 1, 1, 3, 0, 0],
[ 104, 1, 1, 4, 0, 0, 0],
[ 0, 105, 1, 1, 5, 0, 0],
[ 0, 1, 1, 0, 0, 0, 0]]
The outer loop does not need the index; enumerate
is not needed. You can break the inner loop as soon as a match is found. There is no need to perform any checks on the inner index either.
for l in example_array:
for i, x in enumerate(l):
if x > 1:
l[i] += 100
break