Python – 从记录中删除 K
有时,在使用Python元组时,我们可能会遇到需要从列表中删除所有 K 的问题。此任务可以在许多领域中应用,例如 Web 开发和日常编程。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [(5, 6, 7), (2, 5, 7)]
K = 7
Output : [(5, 6), (2, 5)]
Input :
test_list = [(5, 6, 7), (2, 5, 7)]
K = 5
Output : [(6, 7), (2, 7)]
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们执行获取条件检查和使用列表理解重新创建新列表的任务。
# Python3 code to demonstrate working of
# Remove K from Records
# Using list comprehension
# initializing list
test_list = [(5, 6, 7), (2, 5), (1, ), (7, 8), (9, 7, 2, 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
# Remove K from Records
# Using list comprehension
res = [tuple(ele for ele in sub if ele != K) for sub in test_list]
# printing result
print("The records after removing K : " + str(res))
输出 :
The original list is : [(5, 6, 7), (2, 5), (1, ), (7, 8), (9, 7, 2, 1)]
The records after removing K : [(5, 6), (2, 5), (1, ), (8, ), (9, 2, 1)]
方法 #2:使用filter()
+ lambda
上述功能的组合可以用来解决这个问题。在此,我们使用 filter() 和 lambda 功能执行删除所有 K 的任务。
# Python3 code to demonstrate working of
# Remove K from Records
# Using filter() + lambda
# initializing list
test_list = [(5, 6, 7), (2, 5), (1, ), (7, 8), (9, 7, 2, 1)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 7
# Remove K from Records
# Using filter() + lambda
res = [tuple(filter(lambda ele: ele != 0, sub)) for sub in test_list]
# printing result
print("The records after removing K : " + str(res))
输出 :
The original list is : [(5, 6, 7), (2, 5), (1, ), (7, 8), (9, 7, 2, 1)]
The records after removing K : [(5, 6), (2, 5), (1, ), (8, ), (9, 2, 1)]