Python – 保留出现 N 次 K 的记录
有时,在使用Python元组列表时,我们可能会遇到一个问题,即我们需要保留所有出现 K 次的记录。此类问题可能出现在 Web 开发和日常编程等领域。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(4, 5, 5, 4), (5, 4, 3)], K = 5, N = 2
Output : [(4, 5, 5, 4)]
Input : test_list = [(4, 5, 5, 4), (5, 4, 3)], K = 5, N = 3
Output : []
方法 #1:使用列表理解 + count()
上述功能的组合可以用来解决这个问题。在此,我们使用列表推导执行计算出现次数和条件以及迭代的任务。
Python3
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using count() + list comprehension
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using count() + list comprehension
res = [ele for ele in test_list if ele.count(K) == N]
# printing result
print("Filtered tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using list comprehension + sum()
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using list comprehension + sum()
res = [ele for ele in test_list if sum(cnt == K for cnt in ele) == N]
# printing result
print("Filtered tuples : " + str(res))
输出 :
The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]
方法 #2:使用列表理解 + sum()
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 执行计算 K 的总和计数的任务。
Python3
# Python3 code to demonstrate working of
# Retain records with N occurrences of K
# Using list comprehension + sum()
# initializing list
test_list = [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# initializing N
N = 3
# Retain records with N occurrences of K
# Using list comprehension + sum()
res = [ele for ele in test_list if sum(cnt == K for cnt in ele) == N]
# printing result
print("Filtered tuples : " + str(res))
输出 :
The original list is : [(4, 5, 6, 4, 4), (4, 4, 3), (4, 4, 4), (3, 4, 9)]
Filtered tuples : [(4, 5, 6, 4, 4), (4, 4, 4)]