使用循环或其他方法分配变量

2024-09-27 00:11:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把这些代码在for循环,但我有错误。我知道变量不能用循环赋值,也可能是我错了。你知道吗

有办法做到这一点吗?或者有没有其他方法来实现这个目标?你知道吗

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


Tags: textinfordatasizetagaxset
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:28

实现for循环的方式是错误的。你知道吗

而像'pm'+str(i) = ...这样的操作将不起作用,因为它是一个字符串。不是变量。你知道吗

因此,使用list,您可以

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)

还要注意tag是在循环外初始化的。否则,它将在每次迭代中重置。你知道吗

相关问题 更多 >

    热门问题