本文實例為大家分享了python實現(xiàn)二維數(shù)組的對角線遍歷,供大家參考,具體內(nèi)容如下
第一種情況:從左上角出發(fā),右下角結束
要完成的事情,就像下圖:

話不多說,直接上Python實現(xiàn)代碼與結果展示:
# 輸出遍歷的索引與其對應的值A = [[1,2,3],  [4,5,6],  [7,8,9]]n = len(A)for i in range(n+n-1): for j in range(i+1):  k = i-j  if k<n and k>=0 and j<n:   print("對應索引:",j,k, "  對應值:",A[j][k])
第二種情況:從右上角出發(fā),左下角結束
情況如下:

原以為這一種的解決方式會和上一種的一樣的簡單,但是嘗試一下失敗了,只有一個“曲線救國”的解決辦法:依據(jù)索引關系輸出結果
自己的Python實現(xiàn)代碼與結果展示:
A = [[1,2,3],   [4,5,6],   [7,8,9]]# 得到下標索引size = len(A)list_i = []   # 第一索引list_j = []   # 第二索引正序l1 = []     # 第二索引逆序for m in range(2*size-1):  for n in range(m+1):    k = m-n    if k<size and k>=0 and n<size:      list_i.append(n)      list_j.append(k)print("第一索引i:/n", list_i)print("第二索引j:")for i in range(len(list_j)):  a = list_j.pop()  l1.append(a)print(l1, "/n"*2, "輸出結果如下:")for i in range(len(list_i)):  print(A[list_i[i]][l1[i]], end= " ")
前輩jiaobuchong的Python實現(xiàn)代碼與結果展示:
arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]for each_arr in arr1: print(each_arr)tem_arr = [] # 用來記錄數(shù)組值rows = len(arr1)cols = len(arr1[0])def isValidIndex(x, n): return (x >= 0 and x < n) # 每一行的每個值的數(shù)組下標的差都一樣,for i in range(cols * 2 - 1): # 共輸出 cols * 2 - 1 行 diff = cols - i - 1 # 每一行的差 for j in range(cols): # 數(shù)組中每一個值的下標范圍是0到cols k = j - diff # 通過一個下標值計算另一個下標值 if isValidIndex(k, rows): # 剩下就是判斷這些下標值是否滿足當前的情況, 這一步不怎么好理解 print(arr1[k][j], ' ', end='') print()

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答