Colorful Life2010

Tag: 字典 | 记录数: 2
Python中字典操作的常用方法
Weather:13~23度,西南风4~5级,晴

  当然说字典,那也就有一些常用方法

------------------------清除------------------------
clear()方法,将字典所有内容清除:
>>> d = {'age' : 12, 'name' : 'bob'}
>>> d
{'age': 12, 'name': 'bob'}
>>> d.clear()
>>> d
{}

有人可能会问为什么不直接d={}?
看下面的例子:
>>> d = {'age' : 12, 'name' : 'bob'}
>>> x = d
>>> d = {}
>>> x
{'age': 12, 'name': 'bob'}.....

Python下为字典排序
Weather:阴 ,东南风 4-5级 ,最低气温4 ℃

<p># (IMHO) the simplest approach:<br /> def sortedDictValues1(adict):<br /> &nbsp;&nbsp;&nbsp; items = adict.items()<br /> &nbsp;&nbsp;&nbsp; items.sort()<br /> &nbsp;&nbsp;&nbsp; return [value for key, value in items]<br /> <br /> # an alternative implementation, which<br /> # happens to run a bit faster for large<br /> # dictionaries on my machine:<br /> def sortedDictValues2(adict):<br /> &nbsp;&nbsp;&nbsp;...</p>