zoukankan      html  css  js  c++  java
  • python排序的两个方法

    前言

    python的排序有两个方法,一个是list对象的sort方法,另外一个是builtin函数里面sorted,主要区别:

    • sort仅针对于list对象排序,无返回值, 会改变原来队列顺序
    • sorted是一个单独函数,可以对可迭代(iteration)对象排序,不局限于list,它不改变原生数据,重新生成一个新的队列

    本篇是基于python3.6讲解的,python2会多一个cmp参数,cmp函数在python3上已经丢弃了
    cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果x == y返回 0, 如果 x > y 返回 1。

    sort方法

    1.sort是list对象的方法,通过.sort()来调用

    >>> help(list.sort)
    Help on method_descriptor:
    
    sort(...)
        L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
    
    >>>
    

    2.参数说明:

    • key 用列表元素的某个属性或函数进行作为关键字(此函数只能有一个参数)
    • reverse 排序规则. reverse = True 降序 或者 reverse = False 升序,默认升序
    • return 无返回值

    3.使用方法介绍

    # coding:utf-8
    
    a = [-9, 2, 3, -4, 5, 6, 6, 1]
    
    # 按从小到大排序
    a.sort()
    print(a)  # 结果:[-9, -4, 1, 2, 3, 5, 6, 6]
    
    # 按从大到小排序
    a.sort(reverse=True)
    print(a)  # 结果:[6, 6, 5, 3, 2, 1, -4, -9]
    

    4.key参数接受的是函数对象,并且函数只能有一个参数,可以自己定义一个函数,也可以写个匿名函数(lambda)

    # coding:utf-8
    # Python学习交流群:778463939
    
    a = [-9, 2, 3, -4, 5, 6, 6, 1]
    # 按绝对值排序
    def f(x):
        return abs(x)
    a.sort(key=f)
    print(a)   # 结果:[1, 2, 3, -4, 5, 6, 6, -9]
    
    # 1、list对象是字符串
    b = ["hello", "helloworld", "he", "hao", "good"]
    # 按list里面单词长度倒叙
    b.sort(key=lambda x: len(x), reverse=True)
    print(b)   # 结果:['helloworld', 'hello', 'good', 'hao', 'he']
    
    # 2、.list对象是元组
    c = [("a", 9), ("b", 2), ("d", 5)]
    
    # 按元组里面第二个数排序
    c.sort(key=lambda x: x[1])
    print(c)  # 结果:[('b', 2), ('d', 5), ('a', 9)]
    
    # 3、list对象是字典
    d = [{"a": 9}, {"b": 2}, {"d":5}]
    
    d.sort(key=lambda x: list(x.values())[0])
    print(d)  # 结果:[{'b': 2}, {'d': 5}, {'a': 9}]
    

    sorted函数

    1.sorted是python里面的一个内建函数,直接调用就行了

    >>> help(sorted)
    Help on built-in function sorted in module builtins:
    
    sorted(iterable, key=None, reverse=False)
        Return a new list containing all items from the iterable in ascending order.
    
        A custom key function can be supplied to customize the sort order, and the
        reverse flag can be set to request the result in descending order.
    
    >>>
    

    2.参数说明

    • iterable 可迭代对象,如:str、list、tuple、dict都是可迭代对象(这里就不局限于list了)
    • key 用列表元素的某个属性或函数进行作为关键字(此函数只能有一个参数)
    • reverse 排序规则. reverse = True 降序或者 reverse = False 升序,默认升序
    • return 有返回值值,返回新的队列

    3.使用方法介绍

    # coding:utf-8
    # Python学习交流群:778463939
    
    a = [-9, 2, 3, -4, 5, 6, 6, 1]
    
    # 按从小到大排序
    b = sorted(a)
    print(a)   # a不会变
    print(b)   # b是新的队列 [-9, -4, 1, 2, 3, 5, 6, 6]
    
    # 按从大到小排序
    c = sorted(a, reverse=True)
    print(c)  # 结果:[6, 6, 5, 3, 2, 1, -4, -9]
    

    4.可迭代对象iterable都可以排序,返回结果会重新生成一个list

    # 字符串也可以排序
    
    s = "hello world!"
    d = sorted(s)
    print(d)  # 结果:[' ', '!', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
    
    # 元组也可以排序
    t = (-9, 2, 7, 3, 5)
    n = sorted(t)
    print(n)  # 结果:[-9, 2, 3, 5, 7]
    
    # dict按value排序
    f = {"a": 9, "b": 2, "d": 5}
    g = sorted(f.items(), key=lambda x: x[1])
    print(g)  # 结果:[('b', 2), ('d', 5), ('a', 9)]
    
  • 相关阅读:
    Oracle内置函数之数值型函数
    【Java基础】java 获得本日,本周,本月的时间戳区间
    【mybatis】1、入门CURD基本操作(环境搭建)
    【hibernate】<第二节>hibernate的一对多映射(基本类型)
    Hibernate Java、Hibernate、SQL 之间数据类型转换
    【hibernate】<第一节>hibernate简单入门
    WebService wsdl没有types的问题
    Hibernate出现javax.naming.NoInitialContextException 错误的解决办法
    easyui 的 DataGrid View 使用
    Date与String之间相互转换
  • 原文地址:https://www.cnblogs.com/djdjdj123/p/13916583.html
Copyright © 2011-2022 走看看