zoukankan      html  css  js  c++  java
  • Python学习之sort与sorted

    >>> a=[9,8,7,6,5,4,3,2,1]
    >>> a.sort()
    >>> a
    >>> [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>
    >>> b=[9,8,7,6,5,4,3,2,1]
    >>> c=sorted(b)
    >>> b
    [9,8,7,6,5,4,3,2,1]
    >>> c
    [1, 2, 3, 4, 5, 6, 7, 8, 9]

    由以上可知,list.sort()方法会按照升序将列表重新排列,不会保留原列表。

    而sorted()会返回副本,原始输入不变。

    sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序,比较函数的定义是,传入两个待比较的元素x,y,如果x应该排在y前面,则返回-1;如果x应排在y后面,则返回1;如果x与y相等,则返回0。

    因此,如果要实现倒序排列,只需编写一个reverse_cmp函数:

    def reversed_cmp(x, y):
        if x > y:
            return -1
        if x < y:
            return 1
        return 0
    

    如此,调用sorted()并传入reverse_cmp就可以实现倒序排列:

    >>> sorted([36, 5, 12, 9, 21], reversed_cmp)
    [36, 21, 12, 9, 5]
    

    任务:

    对该字符串排序,忽略大小写

    输入:['bob', 'about', 'Zoo', 'Credit']

    输出:['about', 'bob', 'Credit', 'Zoo']

    思路:

    sorted()对字符串排序时,默认按照ASCII码大小比较,顺序是A,B,C...X,Y,Z...a,b,c...x,y,z

    def cmp_ignore_case(s1, s2):
        u1 = s1.upper()
        u2 = s2.upper()
        if u1 < u2:
            return -1
        if u1 > u2:
            return 1
        return 0
    print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)
    

      

  • 相关阅读:
    09、AppBarControl
    15、ScrollViewerSample
    11、DataBinding
    18、Compression
    关于创建oracle dblink 过程的几点心得吧
    教你如何玩转DK血
    DK需要知道的事
    Displaying Dynamic KML with ASP.NET
    WLK:裁缝/附魔350450速冲攻略
    WLK狂暴,防御战士的一点心得.
  • 原文地址:https://www.cnblogs.com/tzuxung/p/6193467.html
Copyright © 2011-2022 走看看