Chinaunix首页 | 论坛 | 博客
  • 博客访问: 202465
  • 博文数量: 32
  • 博客积分: 3319
  • 博客等级: 中校
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-26 21:40
文章分类

全部博文(32)

文章存档

2010年(31)

2009年(1)

分类: Python/Ruby

2010-04-26 11:34:11

在Python2.7.x版本中, collections类增加了OrderedDict, 用法如下:
 

pywugw@pywugw-laptop:~$ /usr/local/bin/python2.7
Python 2.7b1 (r27b1:79927, Apr 26 2010, 11:44:19)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

#按key排序
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

#按value排序
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

#按key的长度排序
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])


阅读(2688) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~