zoukankan      html  css  js  c++  java
  • 测试面试题集-Python列表去重(5)

    请定义函数,将列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]中的重复元素除去,写出至少3种方法。

    • 方法一:利用集合去重

    list_1=[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
    def func1(list_1):
       return list(set(list_1))
    print('去重后的列表:',func1(list_1))
    

      

    • 方法二:利用for循环

    list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
    def func2(list_2):
        #定义一个空列表
        mylist_2=[]
        #i遍历list_2
        for i in list_2:
            #如果i不在mylist_2,则添加到mylist_2
            if i not in mylist_2:
                mylist_2.append(i)
        print(mylist_2)
    print(func2(list_2))
    

      

    • 方法三:巧用sort()排序

    list_3 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
    def func3(list_3):
      result_list=[]
      temp_list=sorted(list_3)
      i=0
      while i<len(temp_list):
          #如果不在result_list则添加进去,否则i+1
        if temp_list[i] not in result_list:
          result_list.append(temp_list[i])
        else:
          i+=1
      return result_list
    print(func3(list_3))
    

      

    • 方法四:巧用字典

    list_4= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
    def func4(list_4):
        #fromkeys() 函数创建一个新字典,获取新字典的键(键值是唯一的)
        result_list = []
        for i in {}.fromkeys(list_4).keys():
            result_list.append(i)
        return result_list
    print(func4(list_4))
    

      

    • 方法五:利用迭代器

    import itertools
    list_5= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
    def func5(list_5):
        list_5.sort()
        temp_list= itertools.groupby(list_5)
        result_list=[]
        for i,j in temp_list:
            result_list.append(i)
        return result_list
    print(func5(list_5))
    

      运行结果:

      

  • 相关阅读:
    刚刚找到的IP地址对应地区数据库
    SQL2000中像SQL2005中的Row_Number一样获取行号
    KindEditor3.4.4版的ASP.NET版本
    使用程序代码输出论坛回复第X层楼
    IIS上启用Gzip压缩(HTTP压缩)详解(PDF)
    ASP.NET中过滤HTML字符串的两个方法
    七个受用一生的心理寓言
    Android获取其他包的Context实例然后XX(转载)
    android junit基础教程
    java获取web容器地址
  • 原文地址:https://www.cnblogs.com/chenyablog/p/15172766.html
Copyright © 2011-2022 走看看