前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >五种Python方法实现列表去重

五种Python方法实现列表去重

原创
作者头像
ITester软件测试小栈
修改2021-03-23 17:54:49
1.2K0
修改2021-03-23 17:54:49
举报
文章被收录于专栏:全栈测试全栈测试

将列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]去除重复元素。

代码语言:javascript
复制
#方法一:利用集合去重
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))
#[1, 2, 3, 10, 44, 15, 20, 56]

#方法二:用for循环
'''用i遍历list,如果不在新列表中,则添加到新列表,,否则不添加进去,依次循环'''
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)
            return list_2
    print(func2(list_2))
[1, 2, 3, 10, 15, 20, 44, 56]

#[1, 2, 3, 10, 44, 15, 20, 56]

#方法三:用列表的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))
#[1, 2, 3, 10, 15, 20, 44, 56]

#方法四
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))
#[10, 1, 2, 20, 3, 15, 44, 56] 从原来的列表从左到右去取,因此顺序不一样

#方法五
#迭代器模块
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))
#[1, 2, 3, 10, 15, 20, 44, 56]


ITester软件测试小栈(ID:ITestingA),专注于软件测试技术和宝藏干货分享,每周准时更新原创技术文章,每月不定期赠送技术书籍,愿我们在更高处相逢。喜欢记得星标⭐我,每周及时获得最新推送,第三方转载请注明出处。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档