本篇文章为大家展示了怎么去除python中一个列表里重复的项,代码简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
python四种方法实现去除列表中的重复元素:
#第一种,使用集合的方式
def func1(one_list):
return list(set(one_list))
#第二种,使用字典的方式
def func2(one_list):
return {}.fromkeys(one_list).keys()
#第三种,使用列表推导的方式
def func3(one_list):
temp_list=[]
for one in one_list:
if one not in temp_list:
temp_list.append(one)
return temp_list
#第四种,使用排序的方式
def func4(one_list):
result_list=[]
temp_list=sorted(one_list)
i=0
while i<len(temp_list):
if temp_list[i] not in result_list:
result_list.append(temp_list[i])
else:
i+=1
return result_list
if __name__ == '__main__':
one_list=[56,7,4,23,56,9,0,56,12,3,56,34,45,5,6,56]
print func1(one_list)
print func2(one_list)
print func3(one_list)
print func4(one_list)
结果如下:
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[56, 7, 4, 23, 9, 0, 12, 3, 34, 45, 5, 6]
[0, 3, 4, 5, 6, 7, 9, 12, 23, 34, 45, 56]
上述内容就是怎么去除python中一个列表里重复的项,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。