📜  Python – 过滤范围长度元组

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

Python – 过滤范围长度元组

有时,在处理记录时,我们可能希望以这样一种方式过滤记录,即我们需要丢弃不包含构成记录所需元素的确切数量且位于某个范围内的记录。让我们讨论可以执行此任务的某些方式。

方法 #1:使用列表理解 + len()
在这种方法中,我们只是遍历列表并丢弃与构成记录所需的匹配范围长度不匹配的元组。长度的计算由 len() 完成。

# Python3 code to demonstrate working of
# Filter Range Length Tuples
# Using list comprehension + len()
  
# Initializing list
test_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing desired lengths 
i, j = 2, 3
  
# Filter Range Length Tuples
# Using list comprehension + len()
res = [sub for sub in test_list if len(sub) >= i and len(sub) <= j]
      
# printing result
print("The tuple list after filtering range records : " + str(res))
输出 :
The original list is : [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
The tuple list after filtering range records : [(5, 6), (2, 3, 5), (5, 9)]

方法 #2:使用filter() + lambda + len()
上述功能的组合也可用于执行此特定任务。在此,我们只使用 filter() 并使用 lambda函数来过滤范围长度记录。

# Python3 code to demonstrate working of
# Filter Range Length Tuples
# Using filter() + lambda + len()
  
# Initializing list
test_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing desired lengths 
i, j = 2, 3
  
# Filter Range Length Tuples
# Using filter() + lambda + len()
res = list(filter(lambda ele: len(ele) >= i and len(ele) <= j, test_list))
      
# printing result
print("The tuple list after filtering range records : " + str(res))
输出 :
The original list is : [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]
The tuple list after filtering range records : [(5, 6), (2, 3, 5), (5, 9)]