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'
  • 相关阅读:
    文件的上传
    JSP基础知识
    AJAX
    Listener
    Filter(一)
    session
    网络爬虫(9)-xpath解析
    网络爬虫(8)-正则表达式
    网络爬虫(7)-beautifulSoup解析库
    网络爬虫(6)-Requests库
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14447492.html
Copyright © 2011-2022 走看看