打印给定数组的所有对角元素

时间:2017-12-21 18:41:15

标签: python matrix diagonal

a = [['a','b','c'],
    ['d','e','f','g'],
    ['h','i','j','k'],
    ['l','m','n']]

我需要打印给定数组的对角元素,例如输出将是:

[['l'],['h','m'],['d','i','n'],['a','e','j'],['b','f','k'],['c','g']]

1 个答案:

答案 0 :(得分:2)

我想这或多或少是这样的:

    a = [
    ['a','b','c'],
    ['d','e','f','g'],
    ['h','i','j','k'],
    ['l','m','n']
    ]

d = 0
while True:
  array = []
  j = (len(a)-1)-d
  k = 0
  if j<0:
    k= -j
    j = 0
  while j<len(a) and k<len(a[j]):
    array.append(a[j][k])    
    j+=1
    k+=1
  if len(array) == 0:
    break

  print(array)
  d+=1