1
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

2
  • 1
    Any reason not to use a list of tuples to store your cX and cY values? For example: xy = [] and then xy.append((second_canvas.shape[1]//2,0)) etc. Then you can simply iterate over the list: for x,y in xy: Commented Jun 18, 2022 at 10:47
  • I wanted to know how to actually come with solution when faced with identical situation. What you told though, works perfect for the above case. Commented Jun 18, 2022 at 11:36

3 Answers 3

1

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)) 
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

see the documentation here : docs.python.org/3/library/functions.html
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.