如何使嵌套的if仍然循环通过

2024-04-25 00:50:24 发布

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

listup = [{'post': 'up', 'address': 1, 'index': 1}, {'post': 'up', 'address': 1, 'index': 2}, {'post': 'up', 'address': 1, 'index': 3}, {'post': 'up', 'address': 1, 'index': 4}]
listdown = [{'post': 'down', 'address': 1, 'index': 1}, {'post': 'down', 'address': 1, 'index': 3}, {'post': 'down', 'address': 1, 'index': 2}, {'post': 'down', 'address': 1, 'index': 4}]

我试图使listup继续循环,直到它与listdown达到相同的索引,最终完成listup。我确实使用了嵌套的if,但是循环在nexted if之后退出

if len(listup) !=0:
for up in listup:
    if (listup[0]['index'] != listdown[0]['index']):
        print('1 >>', listup[0]) #for debug purpose
        print('2 >>', listdown[0]) #for debug purpose
        print('seen down earlier than it supposed to')
        print(False)
        if listup[0]['index'] == listdown[1]['index']:
            print('11 >>', listup[0]) #for debug purpose
            print('22 >>', listdown[1]) #for debug purpose
            listdown.pop(0)
            listup.pop(0)
            print('---',True) #for debug purpose
        continue  # HOW TO MAKE THIS STILL RUNNING UNTIL LISTUP IS EMPTY
    else:
        print('1 >>', listup[0]) #for debug purpose
        print('2 >>', listdown[0]) #for debug purpose
        listdown.pop(0)
        listup.pop(0)
        print(True) #for debug purpose
else:
    print('listup empty - finished')

这是输出

1 >> {'post': 'up', 'address': 1, 'index': 1}
2 >> {'post': 'down', 'address': 1, 'index': 1}
True
1 >> {'post': 'up', 'address': 1, 'index': 2}
2 >> {'post': 'down', 'address': 1, 'index': 3}
seen down earlier than it supposed to
False
11 >> {'post': 'up', 'address': 1, 'index': 2}
22 >> {'post': 'down', 'address': 1, 'index': 2}
--- True

我希望代码仍然循环通过listup,直到listup为空,这样在返回---True之后,它仍然继续返回另一个print,直到listup为空

***应该在两个字典列表listuplistdown之间进行检查的代码,对于这两个列表,每个listup字典都有自己的一对,具有listdown-相同的地址和相同的索引。而且listdown的顺序需要遵循listup的顺序;正如您所看到的,{}中的dict顺序遵循其索引1,2,3,4的顺序,{}中的dict顺序应该是1,2,3,4,但其原始顺序是1,3,2,4。因此,第一个if语句返回早于它应该返回的,并嵌套if以继续检查第二个listupdict,直到它在listdown中遇到它们的对为止。当打印'--True'


Tags: debugtrueforindexif顺序addresspost
1条回答
网友
1楼 · 发布于 2024-04-25 00:50:24

您的目标并不明确,但如果您只是想检查两个列表中的哪些项目具有相同的索引键,或者打印第二个列表中的项目是“太早”还是“太迟”:

for a,b in zip(listup, listdown):
    if b['index'] > a['index']:
        print(f"{b['index']} in b seen too early")
    elif b['index'] < a['index']:
        print(f"{b['index']} in b seen too late")
    else:
        print('True')

输出:

True
3 in b seen too early
2 in b seen too late
True

相关问题 更多 >