• Python排序功能进阶


    sortedsort()

    li = [9, 1, 8, 2, 7, 3, 6, 4, 5]
    
    s_li = sorted(li)
    
    print ('Sorted Variable: 	', s_li)
    
    li.sort()
    
    print ('Original Variable: 	', li)
    

    输出结果:

    Sorted Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]
    Original Variable: [1, 2, 3, 4, 5, 6, 7, 8, 9]

    如果:

    li = [9, 1, 8, 2, 7, 3, 6, 4, 5]
    
    s_li = li.sort()
    
    print(s_li)
    

    输出的结果是:

    None

    Tuple不能使用sort(),只能定义一个新的变量=sorted(a_tuple)

    class Employee():
        def __init__(self, name, age, salary):
            self.name = name
            self.age = age
            self.salary = salary
    
        def __repr__(self):
            return '({},{},${})'.format(self.name, self.age, self.salary)
    
    e1 = Employee('Carl', 37, 70000)
    e2 = Employee('Sarah', 29, 80000)
    e3 = Employee('John', 43, 90000)
    
    employees = [e1, e2, e3]
    
    
    def e_sort(emp):
        return emp.name
    
    s_employees = sorted(employees, key=e_sort)
    
    print(s_employees)
    

    或者利用lambda函数:

    s_employees = sorted(employees, key=lambda e: e.name)
    

    或者使用operator模块中的attrgetter

    s_employees = sorted(employees, key=attrgetter('age'))
    
  • 相关阅读:
    G
    O
    M
    K-Hero
    J
    G
    F
    Codeforces Round #327 (Div. 2) A Wizards' Duel (水题)
    C++各大有名科学计算库(转)
    矩阵算法 高斯消元 行列式 矩阵的秩
  • 原文地址:https://www.cnblogs.com/yaos/p/14014356.html
Copyright © 2020-2023  润新知