![](/img/trans.png)
[英]How to use enumerate function in python to get the count of the iteration in a for loop?
[英]How do you use the range function to count from 0 to 8 by increments of 1 for each iteration in a for loop
我有一個三重 for 循環,它創建一個從 0 0 到 2 2 的 1 行和 2 列數字集合。第三個 for 循環從 0 計數到 8。代碼如下所示:
for N in range(0,3):
for K in range(0,3):
print(N,K)
for P in range(0,9):
print(P)
如果你運行這段代碼,你會得到明顯的 output:
0 0
0
1
2
3
4
5
6
7
8
0 1
0
1
2
3
4
5
6
7
8
0 2
0
1
2
3
4
5
6
7
8
...
等等。 在 NK 打印輸出之后,我想要的不是 0 到 8 的 output,而是看起來像這樣的東西:
0 0
0
0 1
1
0 2
2
1 0
3
1 1
4
1 2
5
2 0
6
2 1
7
2 2
8
我的第一個猜測是一個 if 語句,它說:
if P == Q:
break
其中 Q 是幾組總和,甚至是 N,K 數組。 但是,我想不出獲得想要的 output 的最佳方法。 我確實認為 if 語句是實現我想要的結果的最佳方式,但我不太確定如何處理它。 P 對於我的代碼的 rest 是必需的,因為它將在某些子圖中使用。
由於這只是每次打印時的增量,因此您可以使用N * 3 + K
計算索引
for N in range(0, 3):
for K in range(0, 3):
print(N, K)
print(N * 3 + K)
CODE DEMO
您可以使用zip
並行遍歷兩個可迭代對象。 在這種情況下,其中一個可迭代對象是嵌套列表的結果。 這可以通過使用itertools.product
來處理,如下所示:
import itertools
for (N, K), P in zip(itertools.product(range(3), range(3)), range(9)):
print(N, K)
print(P)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.