Python|打印二维列表的对角线
给定一个二维列表(子列表的长度相等),编写一个Python程序来打印给定二维列表的两条对角线。
例子:
Input : [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output : Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
Input : [['a', 'b'], ['c', 'd']]
Output : Diagonal 1 - ['a', 'd']
Diagonal 2 - ['b', 'c']
方法 #1:使用Python xrange()
我们可以将单行列表理解与 xrange()函数一起使用。 xrange()用于在 for 循环中迭代一定次数。因此,我们在循环的每次迭代中打印 [i][i] 位置的元素。 [在 Python2 中工作]
Python
# Python2 program to print diagonals in 2D list
def printDiagonal(lst):
# To print Primary Diagonal
print('Diagonal 1 -'),
print([lst[i][i] for i in xrange(len(lst))])
# To print Secondary Diagonal
print('Diagonal 2 -'),
print([lst[i][len(lst)-1-i] for i in xrange(len(lst))])
# Driver code
lst = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
printDiagonal(lst)
Python3
# Python3 program to print diagonals in 2D list
def printDiagonal(lst):
# To print Primary Diagonal
print('Diagonal 1 - ', end ="")
print([lst[i][i] for i in range(len(lst))])
# To print Secondary Diagonal
print('Diagonal 2 - ', end ="")
print([lst[i][len(lst)-i-1] for i in range(len(lst))])
# Driver code
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
printDiagonal(lst)
Python3
# Python3 program to print diagonals in 2D list
def printDiagonal(lst):
# To print Primary Diagonal
print('Diagonal 1 - ', end ="")
print([r[i] for i, r in enumerate(lst)])
# To print Secondary Diagonal
print('Diagonal 2 - ', end ="")
print([r[~i] for i, r in enumerate(lst)])
# Driver code
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
printDiagonal(lst)
输出
Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
方法 #2:使用 range()
此方法类似于方法#1。 range() 的优点是它适用于Python的两个版本,即 Python2 和 Python3。
Python3
# Python3 program to print diagonals in 2D list
def printDiagonal(lst):
# To print Primary Diagonal
print('Diagonal 1 - ', end ="")
print([lst[i][i] for i in range(len(lst))])
# To print Secondary Diagonal
print('Diagonal 2 - ', end ="")
print([lst[i][len(lst)-i-1] for i in range(len(lst))])
# Driver code
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
printDiagonal(lst)
输出
Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]
方法 #3:使用 enumerate()
Python enumerate()也是上述方法的替代方法。它使用两个变量 'i' 和 'r' 两个遍历 enumerate(lst) 并简单地返回 'r' 的第 i个元素。
Python3
# Python3 program to print diagonals in 2D list
def printDiagonal(lst):
# To print Primary Diagonal
print('Diagonal 1 - ', end ="")
print([r[i] for i, r in enumerate(lst)])
# To print Secondary Diagonal
print('Diagonal 2 - ', end ="")
print([r[~i] for i, r in enumerate(lst)])
# Driver code
lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
printDiagonal(lst)
输出
Diagonal 1 - [1, 5, 9]
Diagonal 2 - [3, 5, 7]