Python – 最大 N 个重复元素
给定元素列表,如果一个元素在列表中的出现增加超过 N,则删除它。
Input : test_list = [6, 4, 6, 3, 6], N = 1
Output : [6, 4, 3]
Explanation : The occurrence 2nd onwards of 6 are removed.
Input : test_list = [6, 4, 6, 3, 6], N = 2
Output : [6, 4, 6, 3]
Explanation : The occurrence 3nd onwards of 6 are removed.
方法 #1:使用循环 + count()
上述功能的组合可以用来解决这个问题。在此,我们执行元素的迭代,并使用 count() 检查 count 是否大于该元素的 N,如果是,则删除该元素。
Python3
# Python3 code to demonstrate working of
# Maximum N repeated Elements
# Using loop + count()
# initializing list
test_list = [5, 7, 7, 2, 5, 5, 7, 2, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing N
N = 2
# Using loop + count()
res = []
for ele in test_list:
# checking of elements occurrence is not greater than N
if res.count(ele) < N:
res.append(ele)
# printing result
print("Extracted elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Maximum N repeated Elements
# Using Counter() + loop
from collections import Counter
# initializing list
test_list = [5, 7, 7, 2, 5, 5, 7, 2, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing N
N = 2
# Using Counter() + loop
res = []
temp = Counter(test_list)
for key, ele in temp.items():
# Conditional check for size decision during append
if ele <= N:
res.extend([key for idx in range(ele)])
else:
res.extend([key for idx in range(N)])
# printing result
print("Extracted elements : " + str(res))
输出
The original list : [5, 7, 7, 2, 5, 5, 7, 2, 2]
Extracted elements : [5, 7, 7, 2, 5, 2]
方法 #2:使用 Counter() + 循环
这是可以执行此任务的另一种方式。在此,我们使用 Counter() 来执行元素计数,然后如果小于 N,则附加其大小的元素,如果大于,则使用列表推导将元素扩展到 N。不保留顺序。
Python3
# Python3 code to demonstrate working of
# Maximum N repeated Elements
# Using Counter() + loop
from collections import Counter
# initializing list
test_list = [5, 7, 7, 2, 5, 5, 7, 2, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing N
N = 2
# Using Counter() + loop
res = []
temp = Counter(test_list)
for key, ele in temp.items():
# Conditional check for size decision during append
if ele <= N:
res.extend([key for idx in range(ele)])
else:
res.extend([key for idx in range(N)])
# printing result
print("Extracted elements : " + str(res))
输出
The original list : [5, 7, 7, 2, 5, 5, 7, 2, 2]
Extracted elements : [5, 5, 7, 7, 2, 2]