Python - 删除重复数字的数字
给定一个数字列表,任务是编写一个Python程序来删除所有具有重复数字的数字。
例子:
Input : test_list = [4252, 6578, 3421, 6545, 6676]
Output : test_list = [6578, 3421]
Explanation : 4252 has 2 occurrences of 2 hence removed. Similar case for all other removed.
Input : test_list = [4252, 6578, 3423, 6545, 6676]
Output : test_list = [6578]
Explanation : 4252 has 2 occurrences of 2 hence removed. Similar case for all other removed.
方法 #1:使用set() + len() +列表理解
在此,我们使用 set() 执行消除重复元素的任务,然后将长度与原始长度进行比较。如果找到,则返回 True,否则返回 False。
Python3
# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using set() + len() + list comprehension
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
# printing original list
print("The original list is : " + str(test_list))
# set() used to remove digits
res = [sub for sub in test_list if len(set(str(sub))) == len(str(sub))]
# printing result
print("List after removing repeating digit numbers : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using regex()
import re
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
# printing original list
print("The original list is : " + str(test_list))
# regex used to remove elements with repeating digits
regx = re.compile(r"(\d).*\1")
res = [sub for sub in test_list if not regx.search(str(sub))]
# printing result
print("List after removing repeating digit numbers : " + str(res))
输出:
The original list is : [4252, 6578, 3421, 6545, 6676]
List after removing repeating digit numbers : [6578, 3421]
方法#2:使用regex()
适当的正则表达式也可用于仅检查每个数字重复一次的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Remove numbers with repeating digits
# Using regex()
import re
# initializing list
test_list = [4252, 6578, 3421, 6545, 6676]
# printing original list
print("The original list is : " + str(test_list))
# regex used to remove elements with repeating digits
regx = re.compile(r"(\d).*\1")
res = [sub for sub in test_list if not regx.search(str(sub))]
# printing result
print("List after removing repeating digit numbers : " + str(res))
输出:
The original list is : [4252, 6578, 3421, 6545, 6676]
List after removing repeating digit numbers : [6578, 3421]