分享Python列表去重的几种方法

本文介绍了Python列表去重的几种方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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

方法一:利用集合去重

1

2

3

4

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循环

1

2

3

4

5

6

7

8

9

10

11

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()排序

1

2

3

4

5

6

7

8

9

10

11

12

13

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

4

5

6

7

8

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))

方法五:利用迭代器

1

2

3

4

5

6

7

8

9

10

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))

运行结果:

到此这篇关于Python列表去重的文章就介绍到这了,希望对大家的学习有所帮助!

转自:微点阅读    https://www.weidianyuedu.com

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值