[tip]字典排序

3 views
Skip to first unread message

Zoom.Quiet

unread,
May 21, 2007, 6:35:44 AM5/21/07
to Python.cn@google, python-chinese列表
非常经典的需求,一直以为自个儿会的...
e.g
myDict ={"url12.html":12
,"url1112.html":212
,"url346.html":1333
,"url222.html":12
...}
期望按照值的排序进行输出,值有可能一样;
原先以为可以使用外部数组排序后比对输出的,因为值可能重复才发觉不成;
询问 xyb,dreamingk 才知道,原来有内置函式支持的!
"""sorted( iterable[, cmp[, key[, reverse]]])
Return a new sorted list from the items in iterable. The optional
arguments cmp, key, and reverse have the same meaning as those for the
list.sort() method. New in version 2.4.
"""
从2.4 开始数组的排序可以指定键位置!
所以:
for k, v in sorted(myDict.items()
, key=lambda x: x[1]
,reverse=True):
print k,v
就可以获得从大到小的排序字典输出了

要仔细看内置函式哪....

--
'''Time is unimportant, only life important!
http://zoomquiet.org
blog@http://blog.zoomquiet.org/pyblosxom/
wiki@http://wiki.woodpecker.org.cn/moin/ZoomQuiet
scrap@http://floss.zoomquiet.org
douban@http://www.douban.com/people/zoomq/
____________________________________
Pls. use OpenOffice.org to replace M$ Office.
http://zh.openoffice.org
Pls. use 7-zip to replace WinRAR/WinZip.
http://7-zip.org/zh-cn/
You can get the truely Freedom 4 software.
'''

Qiangning Hong

unread,
May 21, 2007, 6:53:14 AM5/21/07
to pyth...@googlegroups.com
On 5/21/07, Zoom. Quiet <zoom....@gmail.com> wrote:
> for k, v in sorted(myDict.items()
> , key=lambda x: x[1]
> ,reverse=True):
> print k,v
> 就可以获得从大到小的排序字典输出了

a better and quicker way:

from operator import itemgetter
sorted(myDict.iteritems(), key=itemgetter(1), reverse=True)

:)

--
Qiangning Hong
http://www.douban.com/people/hongqn/

Zoom.Quiet

unread,
May 21, 2007, 8:20:40 AM5/21/07
to pyth...@googlegroups.com
On 5/21/07, Qiangning Hong <hon...@gmail.com> wrote:
> On 5/21/07, Zoom. Quiet <zoom....@gmail.com> wrote:
> > for k, v in sorted(myDict.items()
> > , key=lambda x: x[1]
> > ,reverse=True):
> > print k,v
> > 就可以获得从大到小的排序字典输出了
>
> a better and quicker way:
>
> from operator import itemgetter
> sorted(myDict.iteritems(), key=itemgetter(1), reverse=True)
>
好那!又学到好招了!

> :)
>
> --
> Qiangning Hong
> http://www.douban.com/people/hongqn/
>
> >
>

Reply all
Reply to author
Forward
0 new messages