sort

作者: idri | 来源:发表于2017-09-04 21:54 被阅读0次

    字典

    # coding:utf-8
    
    adict = {'a':1,'t':5, 'b':5, 'e':4}
    print adict.keys()
    # ['a', 'b', 'e', 't']
    
    print adict.values()
    # [1, 5, 4, 5]
    
    print adict.items(), '\n', type(adict.items()[0]), '\n'
    # [('a', 1), ('b', 5), ('e', 4), ('t', 5)]
    # <type 'tuple'> 
    
    # 先按照value排序
    def sortedDictValues1(adict):
        items = adict.items()
        items.sort()
        return [value for key,value in items]
    print sortedDictValues1(adict)
    
    # [1, 5, 4, 5]
    
    def sortedDictValues2(adict):
        keys = adict.keys()
        keys.sort()
        return [adict[key] for key in keys]
    print sortedDictValues2(adict), '\n'
    
    # 根据value排序,打印value
    def sort_by_value(d):
        items = d.items()
        backitems=[[v[1], v[0]] for v in items]
        backitems.sort()
        print backitems
        return [backitems[i][1] for i in range(0, len(backitems))]
    print sort_by_value(adict)
    
    print '\n一行搞定:'
    
    d = adict
    
    print [v for v in sorted(d.values())]
    
    # 自定义cmp方法, 3.0 已经移除
    # cmp(x[1], y[1]) 表示比较value的大小,返回正数或负数。
    print sorted(d.items(), lambda x, y: cmp(x[1], y[1]))
    
    # tuple排序
    student_tuples = [
            ('john', 'A', 15),
            ('jane', 'B', 12),
            ('dave', 'B', 10),
            ]
    
    # sort by age
    print sorted(student_tuples, key=lambda x: x[2])
    print ''
    
    rows = [
        {'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
        {'fname': 'David', 'lname': 'Beazley', 'uid': 1006},
        {'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
        {'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
    ]
    # 使用itemgetter
    from operator import itemgetter
    # 先按照'lname'排序降序,再按照'uid'排序降序,
    print sorted(rows, key=itemgetter('lname','uid'), reverse=True)
    print ''
    # 先按照'lname'排序正序,相同的再按照'uid'排序降序序。
    # 排序会默认保持原始顺序
    # 优先级高的排序要之后排序
    print sorted(sorted(rows, key=itemgetter('uid'), reverse=True), key=itemgetter('lname'))
    
    
    # 按照uid排序
    # sorted(rows, key=itemgetter(2)) 报错KeyError: 2
    sorted(student_tuples, key=itemgetter(2))
    

    相关文章

      网友评论

          本文标题:sort

          本文链接:https://www.haomeiwen.com/subject/hpbejxtx.html