【问题标题】:for loop with nested while loop - Python带有嵌套while循环的for循环 - Python
【发布时间】:2021-08-21 17:36:29
【问题描述】:

我有以下代码:

lst = [1,2,3,4]

a = 0
i = 0
for i in lst:
    while a < len(lst):
        a += 1
        print(a, i)

我想打印出来

1 1
2 1
3 1
4 1
1 2
2 2
3 2
4 2
1 3
2 3
3 3
4 3
1 4
2 4
3 4
4 4

但是,我正在努力实现这一目标。我只能让它打印列表中的第一项。

1 1
2 1
3 1
4 1

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: python-3.x list loops for-loop while-loop


    【解决方案1】:

    您忘记在 while 循环完成后将 a 恢复为零

    lst = [1,2,3,4]
    
    a = 0
    i = 0
    for i in last:
        while a < len(last):
            a += 1
            print(a, I)
        a = 0 # <-- add this
    

    【讨论】:

      【解决方案2】:

      将 a 的初始化移到第一个循环内,以便在每次迭代时将其重置为 0。

      lst = [1,2,3,4]
      
      i = 0
      for i in lst:
          a = 0
          while a < len(lst):
              a += 1
              print(a, i)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-30
        • 2020-10-09
        • 2013-10-26
        • 1970-01-01
        • 2023-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多