Python列表去重问题:四位数重复数字过滤代码故障排查
问题与修复方案
需求与问题
- 生成仅由2、5、7、9组成的四位数列表
- 过滤列表,移除所有含重复数字的数(如2592、2599)
- 当前代码缺陷:无法移除最后两位数字相同的数(如2599、9255)
原代码
#Please write a program producing four-digit numbers using 2,5,7,9 # In once case, repetition is allowed, in the other it's not. #The answer to the first part of the question: list= [] x=2222 index=0 while 2222<=x<=9999: numList = [int(digit) for digit in str(x)] for t in range(len(numList)): k=int(numList[t]) if k!=2 and k!=5 and k!=7 and k!=9: t-=1 break if t==3: list.insert(index,x) index+=1 x+=1 print("There are {} numbers in total with repetition:".format(len(list))) print((list)) # The answer to the second part of the question: list1=list.copy() for t in range (len(list)): f=0 item=list[t] digit_List = [int(digit) for digit in str(item)] for y in range(len(digit_List)-1): if f==1: break p=int(digit_List[0]) for z in range (1,len(digit_List)): if p==digit_List[z]: f=1 break if len(digit_List)>2: digit_List.pop(y) if f>0: list1.remove(item) print("There are {} numbers in total without repetition:".format(len(list1))) print(list1)
问题根源
你的去重逻辑存在核心漏洞:
- 每次只拿第一个数字和后续数字对比,仅能检测第一个数字是否重复,完全忽略了后面数位之间的重复(比如2599里的两个9,第一个数字是2,和9不重复,所以不会被标记为重复项)
digit_List.pop(y)的操作逻辑混乱,不仅对去重无帮助,还会打乱后续判断流程
修正后的代码
优化版(高效且易读)
# 生成仅由2、5、7、9组成的四位数列表 valid_digits = {2, 5, 7, 9} # 嵌套循环生成,新手更容易理解 num_list = [] for d1 in valid_digits: for d2 in valid_digits: for d3 in valid_digits: for d4 in valid_digits: num = d1 * 1000 + d2 * 100 + d3 * 10 + d4 num_list.append(num) # 也可以用itertools.product简化代码(推荐,需先导入模块) # import itertools # num_list = [int(''.join(map(str, digits))) for digits in itertools.product(valid_digits, repeat=4)] print(f"There are {len(num_list)} numbers in total with repetition:") print(num_list) # 过滤含重复数字的数 unique_num_list = [] for num in num_list: digits = [int(d) for d in str(num)] # 集合自动去重,长度为4说明四个数字都不重复 if len(set(digits)) == 4: unique_num_list.append(num) print(f"\nThere are {len(unique_num_list)} numbers in total without repetition:") print(unique_num_list)
关键改进点
- 生成列表部分:直接遍历每个数位的合法取值,比原代码逐个数字检查效率高得多,逻辑也更清晰
- 去重部分:利用Python集合的特性,将数字转成集合后,若长度等于4则说明所有数字唯一,完美覆盖所有重复场景(包括最后两位重复的情况)
内容的提问来源于stack exchange,提问作者Maz
相关产品推荐
相关产品推荐

