Python Repeated Variable Declaration

Asked 2 years ago, Updated 2 years ago, 69 views

array1 = np.array(img[y+1,x])

array2 = np.array(img[y+2,x])

array3 = np.array(img[y+3,x])

array4 = np.array(img[y+4,x])

array5 = np.array(img[y+5,x])

array6 = np.array(img[y+6,x])

array7 = np.array(img[y+7,x])

array8 = np.array(img[y+8,x])

array9 = np.array(img[y+9,x])

array10 = np.array(img[y+10,x]) ...

I want to declare this recurring variable, but how do I use the for statement to express it?

It has B, G, and R array values such as img[y+1,x] = [0, 255, 255].

python opencv numpy

2022-09-21 16:36

2 Answers

Variable names such as array1 and array2 are cumbersome to use again later.

Instead, it is convenient to declare a list-type variable called array and use it in a way such as array[0] and array[1] to use it later in the for statement.

array = []
for i in range(1, 11):
    array.append(np.array(Img[y+i, x])

# # array[0] = np.array(Img[y+1, x])
# # array[1] = np.array(Img[y+2, x])
# ... 

Because Img is numpy array

array = Img[y+1:y+11, x]

I think this method will be used more often.


2022-09-21 16:36

In Python, coding to declare a public list variable is not a good method.

We recommend using the list compression as below.

array = [np.array(Img[y+i, x]) for i in range(1, 11)]


2022-09-21 16:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.