📜  Python|删除初始 K 列元素

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

Python|删除初始 K 列元素

有时,在处理矩阵数据时,我们可以在每行矩阵的前端附加杂散元素。这有时可能是不受欢迎的,并且希望被删除。让我们讨论可以执行此任务的某些方式。

方法 #1:使用循环 + del + 列表切片
上述功能的组合可用于执行此任务。在此,我们为矩阵中的每一行运行一个循环,并使用 del 删除前面的元素。

# Python3 code to demonstrate working of
# Remove Initial K column elements
# Using loop + del + list slicing
  
# initialize list
test_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize K 
K = 2
  
# Remove Initial K column elements
# Using loop + del + list slicing
for sub in test_list: del sub[:K]
  
# printing result
print("Matrix after removal of front elements from rows : " + str(test_list))
输出 :
The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
Matrix after removal of front elements from rows : [[4], [6], [1]]

方法#2:使用列表理解+列表切片
上述功能的组合也可用于执行此任务。在此,我们只对每一行进行迭代并使用列表切片删除前面的元素。

# Python3 code to demonstrate working of
# Remove Initial K column elements
# Using list comprehension + list slicing
  
# initialize list
test_list = [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
  
# printing original list 
print("The original list : " + str(test_list))
  
# initialize K 
K = 2
  
# Remove Initial K column elements
# Using list comprehension + list slicing
res = [ele[K:] for ele in test_list]
  
# printing result
print("Matrix after removal of front elements from rows : " + str(res))
输出 :
The original list : [[1, 3, 4], [2, 4, 6], [3, 8, 1]]
Matrix after removal of front elements from rows : [[4], [6], [1]]