简体   繁体   English

嵌套for循环意外输出

[英]Nested for loop unexpected output

I've been trying to make a nested for loop, but for some reason the inside one only loops once and I can't figure out why. 我一直在尝试制作一个嵌套的for循环,但是由于某种原因,内部循环只循环了一次,我不知道为什么。 I've already reduced my code to the bare minimum just to figure out whats happening: 我已经将代码减少到最低限度,只是为了了解发生了什么事情:

pupil = db.session.query(Pupil).all()
result = db.session.query(Pupil_OLD).all()
for row in pupil:
    for sublist in result:   
        print("sublist"+str(sublist.PUPIL_ID))
    print("pupil"+str(row.PUPIL_ID))

This produces: 这将产生:

pupil1
sublist1
sublist2
sublist3
pupil2
pupil3

While it should produce 虽然应该产生

pupil1
sublist1
sublist2
sublist3
pupil2
sublist1
sublist2
sublist3
pupil3
sublist1
sublist2
sublist3

Does anyone have an idea what I'm doing wrong? 有人知道我在做什么错吗?

I assume result is a generator which is reaching the end. 我认为result是一个即将到达终点的发电机。

You can reset it like so: 您可以像这样重置它:

pupil = db.session.query(Pupil).all()
for row in pupil:
    result = db.session.query(Pupil_OLD).all()
    for sublist in result:   
        print("sublist"+str(sublist.PUPIL_ID))
    print("pupil"+str(row.PUPIL_ID))

Converting it to a list is another option, but you'd be missing out on cool generators ;) 将其转换为列表是另一种选择,但您会错过酷炫的发电机;)

My love for generator's aside, if resetting it means re-querying a database, you might be better off with the list. 除了对生成器的热爱,如果重置它意味着重新查询数据库,那么使用列表可能会更好。

You should rather do something like 你应该做类似的事情

pupil = db.session.query(Pupil).all()
result = list(db.session.query(Pupil_OLD).all())

So the result of db.session.query(Pupil_OLD).all() which appears to be a generator, is converted to a list which won't be consumed like your generator is. 因此,似乎是生成器的db.session.query(Pupil_OLD).all()的结果将转换为一个列表,该列表将不会像生成器那样被消耗。

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

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