Python的字典操作
Python的字典操作
Python提供了多种应用于字典的操作。因为字典为容器,内建len函数可以将字典当作单一参数使用听切返回字典对象中项目(键/值对)的数目。
字典会员
在Python2.2以及后面版本,D中的k运算符检测是否对象k是字典D中的键。如果是返回True如果不是返回False。相似的,
索引一个字典
字典D中的值与相关的键k被索引表示为:D[k]。索引字典没有的键会引起意外。例如:
d = { 'x':42, 'y':3.14, 'z':7 }
d['x']
# 42
d['z']
# 7
d['a']
# raises exception
平整赋值到一个使用还不在字典中的键的索引(例如,D[newkey]=value)是一个可行的操作,该操作加载键和值到字典里新的项目中。例如:
d = { 'x':42, 'y':3.14, 'z':7 }
d['a'] =
16
# d is now {'x':42,'y':3.14,'z':7,'a':16}
del
D[k]中的del语句,删除字典中拥有键k的项目。如果k不是字典D中的键,del
D[k]就会引起意外。
字典方法
字典对象提供了多种方法,如下表格所示。非变异方法返回结果,但不改变它们使用的对象。在下面列表中,D和D1代表任何字典对象,k代表D中任何有效的键,x为任何对象。
方法
描述
Non-mutating methods
D.copy( )
Returns a (shallow) copy of the dictionary
D.has_key(k)
Returns True if k is a key in D, otherwise returns False
D.items( )
Returns a copy of the list of all items (key/value pairs) in
D
D.keys( )
Returns a copy of the list of all keys in D
D.values( )
Returns a copy of the list of all values in D
D.iteritems( )
Returns an iterator on all items(key/value pairs) in D
D.iterkeys( )
Returns an iterator o
相关文档:
Python中函数参数的传递是通过“赋值”来传递的。但这条规则只回答了函数参数传递的“战略问题”,并没有回答“战术问题”,也就说没有回答怎么赋值的问题。函数参数的使用可以分为两个方面,一是函数参数如何定义,二是函数在调用时的参数如何解析的。而后者又是由前者决定的。函数参数的定 ......
PEP 0263
Defining Python Source Code Encodings
Python will default to ASCII as standard encoding if no other
encoding hints are given.
To define a source code encoding, a magic comment must
be placed into the source files either as first or second
line in the file, suc ......
2009-11-16
Collin Winter是Python社区一位颇具影响力的开发者,他曾是CPython项目的核心开发者之一、也曾是Unladen Swallow(见文末注释)的核心开发者,参与了很多Python项目的开发。近来传闻Google将在其新项目中限制Python的使用,为此有开发者(以K表示)在Google 论坛中公开询问了Collin Winter,Collin Winte ......
Alex. J. Champandard
赖勇浩(http://laiyonghao.com) 译
原文地址:http://aigamedev.com/open/interviews/inside-galcon-python-ai/
AiGameDev.com在这个周一的 pratical insights 是对Phil Hassey采访。Phil 是一个独立游戏开发者,也是游戏产业社区的活跃分子。他曾赢得2006年4月的 Ludum Dare 比赛(这个比赛关注 ......
Python-String-Function
字符串中字符大小写的变换:
* S.lower() #小写
* S.upper() #大写
* S.swapcase() #大小写互换
* S.capitalize() #首字母大写
&n ......