Home > OS >  How to use for loop to identify variable names
How to use for loop to identify variable names

Time:06-18

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

CodePudding user response:

just loop the list of variables. like

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 the names of the variables, but the variables itself, if you want to loop the names of the variables and acces it, you will found 2 functions : locals() orglobals() it's more recomended 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())

CodePudding user response:

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))

CodePudding user response:

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))
  • Related