在 Python 中,你可以使用 del 语句来删除一维列表中的某个元素,也可以使用 pop() 函数来删除列表中的末尾元素或指定索引处的元素。
如果你想要删除二维数组的某一行,可以使用 del 语句,如下所示:
matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Delete the first row
del matrix[0]
print(matrix) # [[4, 5, 6], [7, 8, 9]]
如果你想要删除指定的行,可以先找到这一行在数组中的索引,然后使用 del 语句删除,如下所示:
matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Find the index of the row to be deleted
row_index = 0
# Delete the row
del matrix[row_index]
print(matrix) # [[4, 5, 6], [7, 8, 9]]
你也可以使用 pop() 函数来删除指定索引处的行,如下所示:
matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Find the index of the row to be deleted
row_index = 0
# Delete the row
matrix.pop(row_index)
print(matrix) # [[4, 5, 6], [7, 8, 9]]
注意:del 语句是永久性地删除列表中的元素,而 pop() 函数是将元素从列表中弹出,但是你可以将弹出的元素赋值给一个变量,以便在后续的代码中使用。