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

发布时间:2020-08-26 10:39:59 作者:Leah
来源:亿速云 阅读:102

本篇文章为大家展示了怎么去除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中一个列表里重复的项,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. C# DataTable去除某列重复的数据
  2. mysql如何去除重复项

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:用C++读取ini文件中Section节名的方法

下一篇:HTML、CSS、JavaScript之间的关系是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》