Rakshit Joshi
Rakshit Joshi

Reputation: 19

How to use for loop to identify variable names

second_canvas = 250*np.ones((300,300,3), dtype="uint8")
cv2_imshow(second_canvas)
cX1,cY1 = (second_canvas.shape[1]//2,0)
cX2,cY2 = (second_canvas.shape[1],second_canvas.shape[0]//2)
cX3,cY3 = (second_canvas.shape[1]//2,second_canvas.shape[0])

for i in range(1,4):
  cv2.circle(second_canvas, (cX'{}',cY'{}').format(i), 175,(0,255,0))

cv2_imshow(second_canvas)

As in here, I want for loop in order to use the respective variable. Can anyone help, please if there is a way to do this? Thanks

Upvotes: 1

Views: 69

Answers (3)

the_cml
the_cml

Reputation: 11

Just loop over the list of variables:

for i in [[cX1,cY1],[cX2,cY2],[cX3,cY3]]:
    cv2.circle(second_canvas, i[0],i[1], 175,(0,255,0))

You're not looping over the names of the variables but the variables themselves. If you want to loop over the names of the variables and access them, you can use two functions, locals() and globals(). It's more recommended to use locals() because it will return a dict of the local variables including the globals ones.

The locals variables are the ones defined and used inside a function.

Example:

for i in zip("cX1 cX2 cX3".split(" "),"cY1 cY2 cY3".split(" ")):
    cv2.circle(second_canvas, locals()[i[0]],locals()[i[1]],175,(0,255,0))

or

for i in zip("cX1 cX2 cX3".split(" "),"cY1 cY2 cY3".split(" ")):
    cv2.circle(second_canvas, globals()[i[0]],globals()[i[1]],175,(0,255,0))

depending if it's inside a function (locals()) or not (globals()).

Upvotes: 1

Edmund
Edmund

Reputation: 36

You can just use two lists like this:

cX, cY = [None] * 3, [None] * 3
cX[0],cY[0] = (second_canvas.shape[1]//2,0)
cX[1],cY[1] = (second_canvas.shape[1],second_canvas.shape[0]//2)
cX[2],cY[2] = (second_canvas.shape[1]//2,second_canvas.shape[0])

for i in range(0,3):
  cv2.circle(second_canvas, (cX[i],cY[i]).format(i), 175,(0,255,0))

Upvotes: 1

Cardstdani
Cardstdani

Reputation: 5223

You can get variables by their names with globals() function. So you will be getting all the instantiated variables in your code and selecting the ones that you need by their name:

variable1 = [1, 2]
print(globals()["variable" + "1"])

Output: [1, 2]

In your case, I think this would be your solution:

cv2.circle(second_canvas, (globals()["cX" + str(i)],globals()["cX" + str(i)]).format(i), 175,(0,255,0))

Upvotes: 0

Related Questions