简体   繁体   English

如何在 for 循环运行时更改 python/django 中的 for 循环变量

[英]How to change for loop variables in python/django while for loop is running

I want to change variables that define a for loop while the loop is running.我想在循环运行时更改定义 for 循环的变量。 It will make more sense when you see the code, so here it is:当你看到代码时它会更有意义,所以它是:

days = form.instance.days

for i in range(0, days + 1):
    days_added = i
    current_end = class_start_date + datetime.timedelta(days=days_added)
    current_end_day = calendar.day_name[datetime.datetime.strptime(str(current_end), '%Y-%m-%d').weekday()]
    if current_end_day == 'Saturday' or current_end_day == 'Sunday':
        days = days + 1

You see, when I run the code days = days + 1 , I want the days for for i in range(0, days + 1): to be updated, so that the number of total loops of the forloop will be increased by 1 whenever days = days + 1 occurs.你看,当我运行代码 days = days days = days + 1时,我希望更新for i in range(0, days + 1):的天数,以便 forloop 的总循环数增加 1每days = days + 1发生时。 days = form.instance.days is increased by 1, but days in for i in range(0, days + 1): is not updated. days = form.instance.days增加了 1,但是days in for i in range(0, days + 1):没有更新。 I hope you guys could help.我希望你们能帮忙。 Thanks.谢谢。

When you write当你写

for i in <expr>:

the expression only gets evaluated once, so you cannot achieve what you want with a for loop.该表达式仅被评估一次,因此您无法通过for循环实现您想要的。 You can use a while instead:您可以改用一段while

i = 0
while i < days + 1:
    days_added = i
    current_end = class_start_date + datetime.timedelta(days=days_added)
    current_end_day = calendar.day_name[datetime.datetime.strptime(str(current_end), '%Y-%m-%d').weekday()]
    if current_end_day == 'Saturday' or current_end_day == 'Sunday':
        days = days + 1
    i += 1

Now the i < days + 1 condition gets evaluated each time, and it will use the updated value of days .现在i < days + 1条件每次都会被评估,它将使用days的更新值。

A while loop may be better suited for your use case. while循环可能更适合您的用例。 You need to establish a condition for it to stop looping while avoiding falling on an infinite loop.您需要为它建立一个停止循环的条件,同时避免陷入无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM