【问题标题】:How to make the nested if still looping thru until如果仍然循环直到直到
【发布时间】:2021-10-19 01:47:56
【问题描述】:
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,但是在下一个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 为空

*** 代码应该检查两个字典列表,listup 和 listdown,对于每个 listup 字典将有自己的 listdown 对 - 相同的地址和相同的索引。还有listdown的顺序需要跟listup的顺序;如您所见,listup 中的 dict 顺序遵循其索引 1,2,3,4 的顺序,listdown 中的 dict 顺序应为 1,2, 3,4,但它们的原始顺序是 1,3,2,4。因此,第一个if 语句返回'比预期更早看到' 并嵌套if 以继续检查listup 的第二个字典,直到它遇到listdown 中的它们对。这就是当listup 的第三个字典没有被检查时出现问题的地方,因为打印时代码停止 '--- True'

【问题讨论】:

  • 请修正缩进。
  • 你不应该修改你正在循环的列表。
  • 有什么方法可以让我循环播放吗?因为我需要修改(弹出)listup
  • continue 的缩进是吗?
  • 我无法弄清楚这段代码应该做什么。请编辑问题以进行解释。

标签: python nested nested-if


【解决方案1】:

您的目标不是很清楚,但如果您只是想检查两个列表中的哪些项目具有相同的索引键,否则打印第二个列表中的项目是“太早”还是“太晚”:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 2021-08-27
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多