You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python统计列表重复元素种类数结果不符合预期如何解决

问题原因

你现有代码的逻辑是遍历列表中的每一个元素,只要该元素出现次数大于1就加入dup列表,因此重复元素出现多少次就会被加入多少次,最终得到的是所有重复元素的实例集合,而非去重后的重复元素种类。另外你原代码中list1.append(items)一行的缩进错误,实际运行会直接报错,需要先修正缩进对齐。

解决方法

方案1:对结果去重后统计长度

最简单的改法是对得到的dup列表先转为集合自动去重,再取长度即可得到重复元素的种类数:

n=int(input("Enter the number of products to be stored in a list : "))
list1=[]
for i in range(n):
    # 修正缩进对齐
    items=int(input("value for product " + str(i+1) + " : "))
    list1.append(items)
    
dup=[]
for a in list1:
    if list1.count(a)>1:
        dup.append(a)

# 转集合去重后取长度
print("Count of duplicate elements in the list: ", len(set(dup)))

方案2:遍历阶段避免重复添加

在添加元素到dup前先判断是否已经存在,直接收集不重复的重复元素种类:

n=int(input("Enter the number of products to be stored in a list : "))
list1=[]
for i in range(n):
    items=int(input("value for product " + str(i+1) + " : "))
    list1.append(items)
    
dup=[]
for a in list1:
    # 新增判断:元素出现次数>1且尚未加入dup列表才添加
    if list1.count(a) > 1 and a not in dup:
        dup.append(a)

print("Count of duplicate elements in the list: ", len(dup))

方案3:使用Counter高效统计(推荐处理长列表)

如果列表长度较大,反复调用count方法会重复遍历列表,效率很低,可以用collections.Counter先统计所有元素的出现次数,再统计重复种类:

from collections import Counter

n=int(input("Enter the number of products to be stored in a list : "))
list1=[]
for i in range(n):
    items=int(input("value for product " + str(i+1) + " : "))
    list1.append(items)

count_map = Counter(list1)
# 统计出现次数大于1的元素个数
dup_count = sum(1 for cnt in count_map.values() if cnt > 1)
print("Count of duplicate elements in the list: ", dup_count)

以上三种方案运行你给出的测试用例,都会输出预期结果1。

内容的提问来源于stack exchange,提问作者Agnel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:45:04