📜  Python|保留特定长度的记录

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

Python|保留特定长度的记录

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

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

# Python3 code to demonstrate working of
# Retain records of specific length
# Using list comprehension + len()
  
# Initializing list
test_list = [(4, 5, 6), (5, 6), (2, 3, 5), (5, 6, 8), (5, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing desired length 
N = 3
  
# Retain records of specific length
# Using list comprehension + len()
res =  [sub for sub in test_list if len(sub) == 3]
      
# printing result
print("The tuple list after removing uneven records: " + str(res))
输出 :
The original list is : [(4, 5, 6), (5, 6), (2, 3, 5), (5, 6, 8), (5, 9)]
The tuple list after removing uneven records: [(4, 5, 6), (2, 3, 5), (5, 6, 8)]

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

# Python3 code to demonstrate working of
# Retain records of specific length
# Using filter() + lambda + len()
  
# Initializing list
test_list = [(4, 5, 6), (5, 6), (2, 3, 5), (5, 6, 8), (5, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Initializing desired length 
N = 3
  
# Retain records of specific length
# Using filter() + lambda + len()
res = list(filter(lambda ele: len(ele) == N, test_list))
      
# printing result
print("The tuple list after removing uneven records: " + str(res))
输出 :
The original list is : [(4, 5, 6), (5, 6), (2, 3, 5), (5, 6, 8), (5, 9)]
The tuple list after removing uneven records: [(4, 5, 6), (2, 3, 5), (5, 6, 8)]