python 列表去重

python去重

通过内置的数据结构去重

  • 使用set数据类型直接进行去重
    当要去重的元素是dict或者[dict]就不是很理想
    通过set去重字典在这里插入图片描述
    通过set去重[dict]
    在这里插入图片描述
    可以直接通过set去重列表、元组、字符串
    在这里插入图片描述
a = (1, 2, 2, 1)
print("去重元组", set(a))  # 去重元组
#
a = [1, 2, 3, 2]
print("去重列表", set(a))  # 去重列表
#
a = '123123'
print("去重字符串", set(a))  # 去重字符串
  • 通过字典的key去重
    因为字典的key是不可以重复的,所以我们就可以通过字典的key来进行去重.
    在这里插入图片描述
    a = [1, 2, 3, 1, 2]
    dict1 = {}
    for i in a:
        dict1[i] = ''
    print("通过字典的可以来进行去重", dict1.keys())
    
  • 通过python内置的函数来去重
    我们可以使用reduce这个方法来进行去重
    在这里插入图片描述
    官方的一段介绍
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

    加粗样式
    a = [1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7]
    def fun1(a, b):
        if not str(b) in a:
            a.append(str(b))
        return a
    c = reduce(fun1, [[], ] + a)
    print(c)	
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值