Python – 根据第 K 列删除自定义行
有时,在使用Python Matrix 时,我们可能会遇到一个问题,即我们需要根据参数列表中存在的第 Kth Column 元素从 Matrix 中删除元素。这可以在许多领域中应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代矩阵的行并从列表中检查第 K 列匹配值并从新列表中排除。
# Python3 code to demonstrate
# Custom Rows Removal depending on Kth Column
# using loop
# Initializing lists
test_list1 = [[3, 4, 5], [2, 6, 8], [1, 10, 2], [5, 7, 9], [10, 1, 2]]
test_list2 = [12, 4, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Initializing K
K = 1
# Custom Rows Removal depending on Kth Column
# using loop
res = []
for ele in test_list1:
if ele[K] not in test_list2:
res.append(ele)
# printing result
print ("The matrix after rows removal is : " + str(res))
输出 :
The original list 1 is : [[3, 4, 5], [2, 6, 8], [1, 10, 2], [5, 7, 9], [10, 1, 2]]
The original list 2 is : [12, 4, 6]
The matrix after rows removal is : [[1, 10, 2], [5, 7, 9], [10, 1, 2]]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在此,我们在一行中使用列表理解以缩短的格式执行类似的任务。
# Python3 code to demonstrate
# Custom Rows Removal depending on Kth Column
# using list comprehension
# Initializing lists
test_list1 = [[3, 4, 5], [2, 6, 8], [1, 10, 2], [5, 7, 9], [10, 1, 2]]
test_list2 = [12, 4, 6]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Initializing K
K = 1
# Custom Rows Removal depending on Kth Column
# using list comprehension
res = [ele for ele in test_list1 if ele[K] not in test_list2]
# printing result
print ("The matrix after rows removal is : " + str(res))
输出 :
The original list 1 is : [[3, 4, 5], [2, 6, 8], [1, 10, 2], [5, 7, 9], [10, 1, 2]]
The original list 2 is : [12, 4, 6]
The matrix after rows removal is : [[1, 10, 2], [5, 7, 9], [10, 1, 2]]