Assigning variables using loop or some other approach

时间:2017-12-18 07:24:36

标签: python matplotlib

I am trying to put these codes in a for loop but I am having error. I know variables can not be assigned using loops or may be I am wrong and there is a way.

Is there a way to achieve this? Or is there an alternative approach to achieve the goal?

pm0=ax.annotate('', (35,10), textcoords='data',size=10)
pm1=ax.annotate('', (35,5), textcoords='data', size=10)
pm2=ax.annotate('', (35,0), textcoords='data', size=10)
pm3=ax.annotate('', (35,-5), textcoords='data',size=10)
pm4=ax.annotate('', (35,10), textcoords='data',size=10)


pm0.set_text(0)
pm1.set_text(1)
pm2.set_text(2)
pm3.set_text(3)
pm4.set_text(4)


#edit for i in range():
  for i in range(5):
     tag=10
     'pm'+str(i)=ax.annotate('', (35,tag), textcoords='data',size=10)
     tag=tag-5
     'pm'+str(i).set_text(i)

enter link description here

1 个答案:

答案 0 :(得分:0)

The way you have implemented your if (ci == i)... // workaround for when the // comparison above won't compile loop is wrong.

And doing something like for will not work because it's a string. Not a variable.

So, using a 'pm'+str(i) = ..., you could do something like

list

Also note that pm = [] tag = 5 for i in range(5): pm[i] = ax.annotate('', (35,tag), textcoords='data',size=10) tag = tag - 5 pm[i].set_text(1) is initialised outside the loop. Otherwise, it will be reset in every iteration.

相关问题