要删除列表中重复项少于k次的项,我们可以采用哈希表(字典)来记录每个元素出现的次数,然后遍历列表,只保留出现次数大于或等于k次的元素。以下是一个Python示例代码:
def remove_items_with_fewer_than_k_duplicates(lst, k):
# 创建一个字典来记录每个元素出现的次数
count_dict = {}
for item in lst:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
# 遍历列表,只保留出现次数大于或等于k次的元素
result = [item for item in lst if count_dict[item] >= k]
return result
# 示例使用
lst = [1, 2, 2, 3, 3, 3, 4, 4]
k = 3
print(remove_items_with_fewer_than_k_duplicates(lst, k)) # 输出应该是 [3, 3, 3]
通过上述方法,你可以有效地删除列表中重复项少于k次的项。
领取专属 10元无门槛券
手把手带您无忧上云