📜  从方阵中删除第一个对角元素的Python程序

📅  最后修改于: 2022-05-13 01:55:34.038000             🧑  作者: Mango

从方阵中删除第一个对角元素的Python程序

给定一个 N*N 维的方阵,任务是编写一个Python程序去除第一条对角线。

例子:

方法 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))


输出:

方法 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))

输出: