问题描述
我有一个奇怪的问题。有人看到我的代码有什么问题吗?c $ c>语句的的Python文档,这不安全(重点是我的):另请参见来自的段落,其中说明了正在发生的事情:
有很多解决方案。您可以按照他们的建议并创建副本。另一种可能性是由于循环的第二个创建一个新的列表,而不是直接修改表单。选择取决于您...
I have a weird problem. Does anyone see anything wrong with my code?
for x in questions: forms.append((SectionForm(request.POST, prefix=str(x.id)),x)) print "Appended " + str(x) for (form, question) in forms: print "Testing " + str(question) if form.is_valid(): forms.remove((form,question)) print "Deleted " + str(question) a = form.save(commit=False) a.audit = audit a.save() else: flag_error = TrueResults in:
Appended Question 50 Appended Question 51 Appended Question 52 Testing Question 50 Deleted Question 50 Testing Question 52 Deleted Question 52It seems to skip question 51. It gets appended to the list, but the for loop skips it. Any ideas?
解决方案You are modifying the contents of the object forms that you are iterating over, when you say:
forms.remove((form,question))According to the Python documentation of the for statement, this is not safe (the emphasis is mine):
See also this paragraph from the Python Language Reference which explains exactly what is going on:
There are a lot of solutions. You can follow their advice and create a copy. Another possibility is to create a new list as a result of your second for loop, instead of modifying forms directly. The choice is up to you...
这篇关于Python for循环跳过其他循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!