zoukankan      html  css  js  c++  java
  • Python sorted函数

    主要是sorted对list(包含元素值是tuple)、字典排序,因为sorted是内置函数,所以不需要导入包

    if __name__ == "__main__":
        a = [5, 7, 6, 3, 4, 1, 2]
        b = sorted(a)  # [5, 7, 6, 3, 4, 1, 2]
    
        a = [('a', 5), ('a', 2), ('c', 3), ('d', 4)]
        
        b = sorted(a, key=lambda x: (x[0], x[1]))
        # 先按x[0]排序,而后再按x[1]排序, [('a', 2), ('a', 5), ('c', 3), ('d', 4)]
    
        b = sorted(a, key=lambda x: (x[0], x[1]), reverse=True)
        # 逆序[('d', 4), ('c', 3), ('a', 5), ('a', 2)]
    
        dic = {"ok": 3, "no": 2, "lizi": 10, "A": 13}   
        res = sorted(dic.items(), key=lambda d: d[0])
        # 返回的是list,每个值是tuple, [('A', 13), ('lizi', 10), ('no', 2), ('ok', 3)]
        
        res = sorted(dic.items(), key=lambda d: d[1])
        # [('no', 2), ('ok', 3), ('lizi', 10), ('A', 13)]
  • 相关阅读:
    hdu 4460spfa用map来实现
    hdu 2579
    hdu 2845
    hdu 4462
    hdu 4557
    hdu 4639
    URAL 2078 Bowling game
    UVA
    HDU 5773 The All-purpose Zero 脑洞LIS
    Codeforces Round #368 (Div. 2) C. Pythagorean Triples 数学
  • 原文地址:https://www.cnblogs.com/AntonioSu/p/15220674.html
Copyright © 2011-2022 走看看