循环时自动赋值变量
p_dil_1、p_dil_2、p_dil_3、p_dil_4 ..... 是我已经制作的变量。
tg1 = p_dil_1
tg2 = p_dil_2
n_dil = 0
while True :
n_dil += 1
# some movement here
if n_dil == 10 :
break
if n_dil <= 10 :
tg1 = p_dil_2
tg2 = p_dil_3
continue
最初的目的是
对于第一个循环,tg1=p_dil_1, tg2=p_dil_2
对于第二个循环,tg1=p_dil_2, tg2=p_dil_3
...
对于第十个循环,tg1=p_dil_10, tg2=p_dil_11
并结束循环
我怎样才能让循环变得简单?
p_dil_1, p_dil_2, p_dil_3, p_dil_4 ..... are variables I have already made.
tg1 = p_dil_1
tg2 = p_dil_2
n_dil = 0
while True :
n_dil += 1
# some movement here
if n_dil == 10 :
break
if n_dil <= 10 :
tg1 = p_dil_2
tg2 = p_dil_3
continue
The original purpose is
For the first loop, tg1=p_dil_1, tg2=p_dil_2
For the second loop, tg1=p_dil_2, tg2=p_dil_3
...
For the tenth loop, tg1=p_dil_10, tg2=p_dil_11
and end the loop
How can I make the loop simple?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一种让事情变得更简单、更干净的方法。
希望这有帮助。
Here is a way to make things a bit simpler and cleaner.
Hope this helps.
您不能动态分配变量。使用列表并使用变量来引用列表中的位置。
You can't assign variables dynamically. Use a list and use a variable to reference the position in the list.
最好的方法是使用字典。另请检查您的逻辑,因为当
n_dil = 10
时,最后一个 if 语句将永远不会执行,因为循环首先中断。请注意,如有必要,for 循环如何从 1 开始(尽管我建议从 0 开始)。此外,for 循环意味着您不需要中断 while 循环或设置和递增
n_dil
。Your best approach would be to use dictionaries. Please also check your logic as when
n_dil = 10
the last, if statement will never be executed as the loop, breaks first.Notice how a for loop can be started at 1 if necessary (although I'd recommend starting at 0). Also the for loop means you don't need to break a while loop or set and increment
n_dil
.您可以将P_DIL_1,P_DIL_2 ...等存储在列表中,您可以说 -
p_dil []
。您可以使用p_dil [0]
和p_dil [1]
初始化
。然后使用TG1
TG2n_dil = 2
开始循环,并注意变量tg1
从上一个迭代中获取tg2
的值。You can store your p_dil_1, p_dil_2... etc in a list, lets say -
p_dil[]
. You can initializetg1
andtg2
withp_dil[0]
andp_dil[1]
. Then start your loop withn_dil = 2
and note that the variabletg1
takes the value oftg2
from the previous iteration.使用for循环怎么样?
What about using for loop?