📜  Python – 删除长度为 K 的元组

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

Python – 删除长度为 K 的元组

给定元组列表,删除所有长度为 K 的元组。

方法#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)]