主题:python小例子之4 -- 列表(list)和字典(dict)数据排序
时间: 2020-08-27来源:ITEYE
前景提要
相关推荐: Python排序 What's New in Python3.0 欢迎大家贴出自己认为优雅简约的ruby代码 python3字典的排序 转载:python list 元素为 dict 时的排序 [work] Python字典dict转换为列表list Python----字典(dict)按值(value)排序 Python3-读取数据并转为dict list字典列表的方法
推荐群组: Python
更多相关推荐
Python         主题:列表(list)和字典(dict)数据排序        环境: winxp pro + sp2 + python2.5         备注: 请注意,凡是在源代码文件中使用了中文字符,请最好保存为utf-8格式         代码:
python 代码
  # sort.py    # 这个类用来演示如何对自定义对象进行排序    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()           测试:保存为文件,直接执行即可

科技资讯:

科技学院:

科技百科:

科技书籍:

网站大全:

软件大全:

热门排行