zoukankan      html  css  js  c++  java
  • python中可迭代对象的排序

    1、字符串排序

    >>> a = "349217"
    >>> b = sorted(a)
    >>> b
    ['1', '2', '3', '4', '7', '9']
    >>> type(b)   ## 返回类型为列表
    <class 'list'>
    >>> c = sorted(a,reverse = True)   ## 逆向排序
    >>> c
    ['9', '7', '4', '3', '2', '1']
    >>> "".join(b)   ## 拼接字符串
    '123479'
    >>> "".join(c)
    '974321'
    >>> a.sort()    ## 字符串不能够就地排序
    Traceback (most recent call last):
      File "<pyshell#345>", line 1, in <module>
        a.sort()
    AttributeError: 'str' object has no attribute 'sort'
    >>> 

    2、列表排序

    >>> a = [3,9,5,2,7]
    >>> b = sorted(a)  ## 使用sorted排序,原变量不变
    >>> b
    [2, 3, 5, 7, 9]
    >>> c = sorted(a,reverse = True)  ## 逆向排序
    >>> c
    [9, 7, 5, 3, 2]
    >>> a
    [3, 9, 5, 2, 7]
    >>> a.sort()   ## 就地排序
    >>> a
    [2, 3, 5, 7, 9]
    >>> a.sort(reverse = True)  ## 就地逆向排序
    >>> a
    [9, 7, 5, 3, 2]

    3、元组排序

    >>> a = (8,2,3,9,5)
    >>> b = sorted(a)   ## sorted排序,原变量不变
    >>> b
    [2, 3, 5, 8, 9]
    >>> c = sorted(a,reverse = True)  ## 逆向排序
    >>> c
    [9, 8, 5, 3, 2]
    >>> a
    (8, 2, 3, 9, 5)
    >>> a.sort()   ## 元组不能就地排序
    Traceback (most recent call last):
      File "<pyshell#374>", line 1, in <module>
        a.sort()
    AttributeError: 'tuple' object has no attribute 'sort'
  • 相关阅读:
    XAMPP安装过程中,出现的问题
    Javascript的数据类型和转换
    Vue组件之间的通信
    vue2.0在页面中自定义组件模块,以及页面与组件之间的数据传递
    本地起一个https服务器
    开发人员初始化操作
    添加环境变量
    公钥~gitlab~免密登录
    class继承随笔
    阿里云ECS随笔
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14447492.html
Copyright © 2011-2022 走看看