我列出了9个元组。我需要在每行中打印3个元组。但是我只能打印2行。我可以知道哪里出了问题吗?
下面是代码中所使用的 Jupyter
List_Tuples = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
Tuples_List = [] # To store 3 tuples at a time and print it
j=0
i=0
while i<9: # Total 9 tuples from index 0 to 8
if j<3: # To restrict 3 tuples in a row
Tuples_List.append(List_Tuples[i])
j+=1
i+=1
continue
print(Tuples_List)
j=0 # Reset j=0 for next row
Tuples_List = [] # Emptying List for storing next 3 tuples
输出为:
[(1, 1), (1, 2), (1, 3)]
[(2, 1), (2, 2), (2, 3)]
为什么不打印[(3, 1), (3, 2), (3, 3)]
?
仅当我将条件更改为
时,它才会打印[(3, 1), (3, 2), (3, 3)]
while i <= 9:
列表索引超出范围
答案 0 :(得分:0)
这是我认为您要缩进代码的方式:
List_Tuples = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
Tuples_List = []
j=0
i=0
while i<9:
if j<3:
Tuples_List.append(List_Tuples[i])
j+=1
i+=1
continue
print(Tuples_List)
j=0
之所以不打印最后一组元组,是因为继续声明。当循环到达continue语句时,它将跳过循环中的所有后续代码,并返回到循环的开始。因此,最后的打印永远不会发生。我们可以通过在循环结束后打印TuplesList
来进行测试。
print(TuplesList)
#[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3,1), (3,2), (3,3)]
答案 1 :(得分:0)
您的代码仅在Tuples_List
为3的乘积时打印生成的i
。但是,由于i
时循环不会继续,因此不会打印最后一个列表。达到9点。
我建议将continue
包裹在另一种情况下,而不是print
来检查j == 3
:
while i<9: -> Total 9 tuples from index 0 to 8
if j<3: -> To restrict 3 tuples in a row
Tuples_List.append(List_Tuples[i])
j+=1
i+=1
if j == 3:
print(Tuples_List)
j=0 -> Reset j=0 for next row
Tuples_List = [] -> Emptying List for storing next 3 tuples
在线查看结果:http://tpcg.io/b1vqhG