ITPub博客

首页 > IT职业 > IT图书 > python怎么样去除一个列表里重复的项

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

IT图书 作者:tomorrowcome 时间:2021-09-11 10:28:18 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学习网,欢迎在线学习!

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/875/viewspace-2835672/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-19

  • 博文量
    122
  • 访问量
    927