• 技术文章 >Python技术 >Python基础教程

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

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-11-07 13:41:21原创5778

    python四种方法实现去除列表中的重复元素:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    #第一种,使用集合的方式

    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)

    结果如下:

    1

    2

    3

    4

    [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学习网,欢迎在线学习!

    专题推荐:python 列表 重复的项
    上一篇:一文了解Python中的递归 下一篇:最全面的12种Python学习方式

    相关文章推荐

    • python中的去除重复项的操作• Python判断列表里是否有重复元素的三种方法• python数组判断是否存在重复元素

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网