Python – 删除长度为 K 的元组
给定元组列表,删除所有长度为 K 的元组。
Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2
Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Explanation : (4, 5) of len = 2 is removed.
Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 3
Output : [(4, 5), (4, ), (1, ), (3, 4, 6, 7)]
Explanation : 3 length tuple is removed.
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们对循环中的所有元素进行迭代,并使用条件执行移除 K 长度元素的所需任务。
Python3
# Python3 code to demonstrate working of
# Remove Tuples of Length K
# Using list comprehension
# initializing list
test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 1
# 1 liner to perform task
# filter just lengths other than K
# len() used to compute length
res = [ele for ele in test_list if len(ele) != K]
# printing result
print("Filtered list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove Tuples of Length K
# Using filter() + lambda + len()
# initializing list
test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 1
# filter() filters non K length values and returns result
res = list(filter(lambda x : len(x) != K, test_list))
# printing result
print("Filtered list : " + str(res))
输出
The original list : [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Filtered list : [(4, 5), (8, 6, 7), (3, 4, 6, 7)]
方法 #2:使用 filter() + lambda + len()
解决这个问题的另一种方法。在此,我们使用 filter() 和 lambda函数执行过滤,以使用 len() 仅提取非 K 长度元素。
Python3
# Python3 code to demonstrate working of
# Remove Tuples of Length K
# Using filter() + lambda + len()
# initializing list
test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 1
# filter() filters non K length values and returns result
res = list(filter(lambda x : len(x) != K, test_list))
# printing result
print("Filtered list : " + str(res))
输出
The original list : [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)]
Filtered list : [(4, 5), (8, 6, 7), (3, 4, 6, 7)]