python列表去重的九种实现方式
实现方式非常多,但都是从几种方法延伸而来,我总结的基本方法有5种,利用复杂的流程控制,if判断进行不同的实现方式,目前延伸出9种实现方式如下,可自行测试,后面发现新的实现方式会持续更新
# 方法一
# 利用集合的元素唯一性,对列表进行去重
def three_question():
li = [11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
se = set(li)
print('列表中不重复元素个数:',len(se))
# three_question()
# 方法二
# 定义一个空列表,用for循环遍历要去重的列表,判断不存在与新定义的空列表的元素就添加实现去#重
def three_question02():
li = [11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
li2 = []
for item in li:
if item not in li2:
li2.append(item)
else:
continue
print('列表中不重复元素个数:',len(li2))
# three_question02()
# 方法三
# 利用嵌套for循环,比对出重复元素进行删除操作,实现列表去重
def three_question03():
li = [11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
num=0
for item in li[0:]:
num+=1
for id in li[num:]:
if id == item:
li.remove(id)
else:
continue
print(li)
print('列表中不重复元素个数:', len(li))
# three_question03()
# 第四种 将值转化为字典的键值,利用键值的唯一性
def three_question04():
print("第三种 将值转化为字典的键值,利用键值的唯一性")
li=[11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
dict1={}
for i in li:
dict1[i]=i
number=len(dict1)
print("列表中不重复的元素个数为:{}".format(number))
# three_question04()
# 方法五:
def three_question05():
li = [11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
li3 =[]
s=set()
for i in li:
if li.count(i) == 1:
if i not in li3:
li3.append(i)
elif li.count(i)>1:
s.add(i)
for se in s:
li3.append(se)
print('不重复元素个数',len(li3))
# three_question05()
# 方法六:
def three_question06():
li = [11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
li3 =[]
s={}
for i in li:
if li.count(i) == 1:
if i not in li3:
li3.append(i)
elif li.count(i)>1:
s[i]=i
for se in s.values():
li3.append(se)
print('不重复元素个数',len(li3))
# three_question06()
#方法七:(利用字典健值去重)字典函数去重
def three_question07():
li=[11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
d = {}
d = d.fromkeys(li)
li2 = list(d.keys())
print(li2)
print('不重复元素个数', len(li2))
# three_question07()
# 方法八:
def three_question08():
li=[11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
li3=[]
index=0
while index < len(li):
if li[index] not in li3:
li3.append(li[index])
index += 1
if index >= len(li):
break
print('不重复元素个数',len(li3))
# three_question08()
# 方法九:
def three_question09():
li=[11, 22, 33, 22, 22, 44, 55, 77, 88, 99, 11]
formatList = list(set(li))
formatList.sort(key=li.index)
print('不重复元素个数',len(formatList))
three_question09()