zoukankan      html  css  js  c++  java
  • 利用内置lambda函数给dict排序

    # sort.py
    #
    -*- coding: gbk -*
    # 这个类用来演示如何对自定义对象进行排序
    class Sortobj:
    a
    = 0
    b
    = ''
    def __init__(self, a, b):
    self.a
    = a
    self.b
    = b
    def printab(self):
    print self.a, self.b

    # 演示对字符串列表进行排序
    samplelist_str
    = ['blue','allen','sophia','keen']
    print samplelist_str
    samplelist_str.sort()
    print samplelist_str

    print
    '\n'

    # 演示对整型数进行排序
    samplelist_int
    = [34,23,2,2333,45]
    print samplelist_int
    samplelist_int.sort()
    print samplelist_int

    print
    '\n'

    # 演示对字典数据进行排序
    sampledict_str
    = {'blue':'5555@sina.com',
    'allen':'222@163.com',
    'sophia':'4444@gmail.com',
    'ceen':'blue@263.net'}
    print sampledict_str
    # 按照key进行排序
    print sorted(sampledict_str.items(), key
    =lambda d: d[0])
    # 按照value进行排序
    print sorted(sampledict_str.items(), key
    =lambda d: d[1])

    # 构建用于排序的类实例
    obja
    = Sortobj(343, 'keen')
    objb
    = Sortobj(56, 'blue')
    objc
    = Sortobj(2, 'aba')
    objd
    = Sortobj(89, 'iiii')

    print
    '\n'

    samplelist_obj
    = [obja, objb, objc, objd]
    # 实例对象排序前
    for obj in samplelist_obj:
    obj.printab()
    print
    '\n'
    # 按照对象的a属性进行排序
    samplelist_obj.sort(lambda x,y: cmp(x.a, y.a))
    for obj in samplelist_obj:
    obj.printab()
    print
    '\n'
    # 按照对象的b属性进行排序
    samplelist_obj.sort(lambda x,y: cmp(x.b, y.b))
    for obj in samplelist_obj:
    obj.printab()

    程序转自:http://www.sqlite.com.cn/MySqlite/11/434.Html

    Work for fun,Live for love!
  • 相关阅读:
    codeforces 407B Long Path
    CodeForces 489C Given Length and Sum of Digits...
    hacker cup 2015 Round 1 解题报告
    hacker cup 2015 资格赛
    Codeforces 486(#277 Div 2) 解题报告
    POJ 3468 A Simple Problem with Integers splay
    Codeforces 484(#276 Div 1) D Kindergarten DP
    求平均值问题201308031210.txt
    I love this game201308022009.txt
    QQ
  • 原文地址:https://www.cnblogs.com/allenblogs/p/2030917.html
Copyright © 2011-2022 走看看