分类: Python/Ruby
2012-12-27 09:22:21
一、python中的List:
Example 3.25. key s, values 和 i tems 函数
>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
>>> params.keys() (1)
['server', 'uid', 'database', 'pwd']
>>> params.values() (2)
['mpilgrim', 'sa', 'master', 'secret']
>>> params.items() (3)
[('server', 'mpilgrim'), ('uid', 'sa'), ('database', 'master'), ('pwd', 'secret')]
二、 函数解析
def info(object, spacing=10, col lapse=1): (1) (2) (3)
"""Print methods and doc strings.
Takes module, class, l ist, dictionary, or string."""
methodList = [method for method in dir(object) if callable(getattr(object, method))]
processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
print "\n".join(["%s %s" % (method.ljust(spacing),processFunc(str(getattr(object, method).__doc__)))
for method in methodList])
if __name__ == "__main__": (4) (5)
print info.__doc__
(1) 该模块有一个声明为 info 的函数。根据它的函数声明可知,它有三个参数:object、spacing 和 collapse。实际上后面两个参数都是可选参数,关于这点你很快就会看到。因为他们在函数中已经事先确定了函数的值,所以在赋值的时候可以不写这两个参数
(2) info 函数有一个多行的 doc string,简要地描述了函数的功能。注意这里并没有提到返回值;单独使用这个函数只是为了这个函数产生的效果,并不是为了它的返回值。
(3) 函数内的代码是缩进形式的。
(4) if __name__ 技巧允许这个程序在自己独立运行时做些有用的事情,同时又不妨碍作为其它程序的模块使用。在这个例子中,程序只是简单地打印出info 函数的 doc string。
(5) if 语句使用 == 进行比较,而且不需要括号。
info 函数的设计意图是提供给工作在 Python IDE 中的开发人员使用,它可以接受任何含有函数或者方法的对象 (比如模块,含有函数,又比如list,含有方法) 作为参数,并打印出对象的所有函数和它们的 doc string。
三、 str函数
str 将数据强制转换为字符串。每种数据类型都可以强制转换为字符串。
Example 4.6. str 介绍
>>> str(1) (1)
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> horsemen
['war', 'pestilence', 'famine']
>>> horsemen.append('Powerbuilder')
>>> str(horsemen) (2)
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper) (3)-------这个是一个模块
"
>>> str(None) (4)
'None'
四、 if语句
number = 23
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.' # New block starts here
print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
print 'No, it is a little higher than that' # Another block
# You can do whatever you want in a block ...
else:
print 'No, it is a little lower than that'
# you must have guess > number to reach here
print 'Done'
五、键盘输入:从键盘输入字符
guess = int(raw_input('Enter an integer : '))