品易云推流 关闭
文章详情页
文章 > Python基础教程 > python怎么样去除一个列表里重复的项

python怎么样去除一个列表里重复的项

头像

爱喝马黛茶的安东尼

2019-11-07 13:41:215460浏览 · 0收藏 · 0评论

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培训视频,尽在python学习网,欢迎在线学习!

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图