• 字典去重与排序


    l=[
        {'name':'egon','age':18,'sex':'male'},
        {'name':'alex','age':73,'sex':'male'},
        {'name':'egon','age':20,'sex':'female'},
        {'name':'egon','age':18,'sex':'male'},
        {'name':'egon','age':18,'sex':'male'},
    ]
    #1
    s=set()
    l1=[]
    for item in l:
        val=(item['name'],item['age'],item['sex'])
        if val not in s:
            s.add(val)
            print(s)
            l1.append(item)
    print(l1)
    
    
    
    
    #2
    def func(items,key=None):
        s=set()
        for item in items:
            val=item if key is None else key(item)
            if val not in s:
                s.add(val)
                yield item
    
    print(list(func(l,key=lambda dic:(dic['name'],dic['age'],dic['sex']))))
    
    
    #3
    l1=[]
    for i in l:
        if i not in l1:
            l1.append(i)
    print(l1)
    
    
    
    
    
    salary_dict = {
        'nick': 3000,
        'jason': 100000,
        'tank': 5000,
        'sean': 2000
    }
    salary_list = list(salary_dict.items())
    print(salary_list)  # [('nick', 3000), ('jason', 100000), ('tank', 5000), ('sean', 2000)]
    
    
    # def func(i):  # i = ('sean', 2000), ('nick', 3000),('tank', 5000),('jason', 100000)
    #     return i[1]  # 2000,3000,5000,100000
    
    
    salary_list.sort(key=lambda i: i[1])  # 内置方法是对原值排序
    # # 按照func的规则取出一堆元素2000,3000,5000,100000
    # # 然后按照取出的元素排序
    print(salary_list)
    
    #用字典的值对字典进行排序
    import operator
    x = {1:2,3:4,5:6,7:8}
    sort_x = sorted(x.items(),key=operator.itemgetter(1))
    print(sort_x)
    # 字典是无序的不可能进行排序,只能转化成另一种方式进行排序,比如元组
    
  • 相关阅读:
    03 . 前端之JavaScipt
    01 . 前端之HTML
    14 . Python3之MysSQL
    13 . Python3之并发编程
    01 . 消息队列之(Kafka+ZooKeeper)
    01 . 分布式存储之FastDFS简介及部署
    03 . Redis集群
    02 . Redis哨兵
    01 . RabbitMQ简介及部署
    01 . Redis简介及部署主从复制
  • 原文地址:https://www.cnblogs.com/SkyOceanchen/p/11413047.html
Copyright © 2020-2023  润新知