从方阵中删除第一个对角元素的Python程序
给定一个 N*N 维的方阵,任务是编写一个Python程序去除第一条对角线。
例子:
Input : test_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]
Output : [[3, 3, 2, 1], [5, 7, 8, 2], [9, 3, 6, 7], [0, 1, 2, 5], [2, 5, 4, 3]]
Explanation : Removed 5, 6, 4, 3, 5 from lists, 1st diagonals.
Input : test_list = [[5, 3, 3, 2], [5, 6, 7, 8], [9, 3, 4, 6], [0, 1, 2, 3]]
Output : [[3, 3, 2], [5, 7, 8], [9, 3, 6], [0, 1, 2]]
Explanation : Removed 5, 6, 4, 3 from lists, 1st diagonals.
方法 1:使用循环和enumerate()
在此我们使用循环遍历每一行,并将元素的索引与行号进行比较,如果发现相等,则省略该元素。
程序:
Python3
# initializing list
test_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [
9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]
# printing original list
print("The original list is : " + str(test_list))
res = []
for idx, ele in enumerate(test_list):
# removing element whose index is equal to row index
res.append([el for idxx, el in enumerate(ele) if idxx != idx])
# printing result
print("Filtered Matrix : " + str(res))
Python3
# initializing list
test_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [
9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to perform task as one liner
res = [[el for idxx, el in enumerate(ele) if idxx != idx]
for idx, ele in enumerate(test_list)]
# printing result
print("Filtered Matrix : " + str(res))
输出:
The original list is : [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]
Filtered Matrix : [[3, 3, 2, 1], [5, 7, 8, 2], [9, 3, 6, 7], [0, 1, 2, 5], [2, 5, 4, 3]]
方法 2:使用列表推导和enumerate()
在此,我们使用列表理解来执行迭代任务,为上述方法提供一种线性解决方案。
程序:
蟒蛇3
# initializing list
test_list = [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [
9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]
# printing original list
print("The original list is : " + str(test_list))
# list comprehension to perform task as one liner
res = [[el for idxx, el in enumerate(ele) if idxx != idx]
for idx, ele in enumerate(test_list)]
# printing result
print("Filtered Matrix : " + str(res))
输出:
The original list is : [[5, 3, 3, 2, 1], [5, 6, 7, 8, 2], [9, 3, 4, 6, 7], [0, 1, 2, 3, 5], [2, 5, 4, 3, 5]]
Filtered Matrix : [[3, 3, 2, 1], [5, 7, 8, 2], [9, 3, 6, 7], [0, 1, 2, 5], [2, 5, 4, 3]]