from collections import Counter
def cap(initial_list, n=2):
counter = Counter()
result = []
for e in initial_list:
if counter[e] < n:
result.append(e)
counter[e] += 1
return result
initial_list = [1,2,1,1,'a','b','a', 'b','b']
cap(initial_list)
def cap(initial_list, n=2):
counts = {}
result = []
for item in initial_list:
if item not in counts:
counts[item] = 1
result.append(item)
else:
if counts[item] < n:
counts[item] += 1
result.append(item)
return result
initial_list = [1,2,1,1,'a','b','a', 'b','b']
cap(initial_list, 2)
from collections import Counter
def cap(initial_list, n=2):
res = []
for k, f in Counter(initial_list).items():
# check frequency of term in list
if f <= n:
res.extend([k]*f)
else:
res.extend([k]*n)
return res
initial_list = [1,2,1,1,'a','b','a', 'b','b']
res = cap(initial_list, 2)
3条答案
按热度按时间kknvjkwl1#
您需要跟踪遇到的值的数量。您可以使用字典(
defaultdict
更好(UPD:正如评论中所建议的Counter
甚至更好)):输出:
ercv8c1e2#
你可以使用一个dict来计算重复的数量,而不需要使用任何库
输出:
5kgi1eie3#
collections.Counter
:根据给定阈值检查频率,并通过逐个案例研究更新结果。