Python – 如果第 N 列为 K,则删除记录
有时在处理记录列表时,我们可能会遇到一个问题,即我们需要根据记录的第 N 个位置存在某个元素来执行删除记录。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,我们对列表中的每个元素进行迭代,如果其第 N 列等于 K,则将其排除。
# Python3 code to demonstrate
# Remove Record if Nth Column is K
# using loop
# Initializing list
test_list = [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 7
# Initializing N
N = 1
# Remove Record if Nth Column is K
# using loop
res = []
for sub in test_list:
if (sub[N] != K):
res.append(sub)
# printing result
print ("List after removal : " + str(res))
输出 :
The original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在此,我们以与上述类似的方式执行此任务,但以一种衬里形式。
# Python3 code to demonstrate
# Remove Record if Nth Column is K
# using list comprehension
# Initializing list
test_list = [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing K
K = 7
# Initializing N
N = 1
# Remove Record if Nth Column is K
# using list comprehension
res = [sub for sub in test_list if sub[N] != K]
# printing result
print ("List after removal : " + str(res))
输出 :
The original list is : [(5, 7), (6, 7, 8), (7, 8, 10), (7, 1)]
List after removal : [(7, 8, 10), (7, 1)]