python 列表去重

python 列表去重,第1张

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)	
    

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/569968.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-09
下一篇2022-04-09

发表评论

登录后才能评论

评论列表(0条)

    保存