以Mark Lutz著的《Python学习手册》为教程,每天花1个小时左右时间学习,争取两周完成。 --- 写在前面的话
2013-7-20 18:30 学习笔记
1,Python中没有Switch语句。同样的功能可以用if语句来实现。例如:
name = 'mathboy'
if name == 'mo':
print 99
elif name == 'linlin':
print 98
elif name == 'mathboy':
print 100
else:
print 90
类似的功能可以利用字典的索引运算简洁实现。例如:
name = 'mathboy'
dic = {'mo': 99,
'linlin': 98,
'mathboy': 100}
print dic[name]
这种实现方式下,默认值可以通过has_key测试、get方法或异常捕获来实现。例如:
name = 'mathboy'
dic = {'mo': 99,
'linlin': 98,
'mathboy': 100}
print dic.get('mathboylinlin')
print dic.get('mo', 'wm')
输出结果为:
None
99
2,Python中,复合语句 = 首行 + “:” + 缩进语句。最顶层的代码没有缩进。缩进是Python语法的一部分,而不仅仅是编程风格。在封闭的()、{}、[]中编写代码,可以横跨数行。使用反斜线 \ 也可以使代码横跨数行,但不是很常用。下面的语句是合法的:
L = ['mathboy',
'linlin',
'mo']
a = 1;b = 2;c = 3;d = 4
if (a == b and
c == d):
print 'equality'
if a == 1: print 'a==1'
3,Python中的not运算符返回True或False,但and和or则返回的是对象。运算的逻辑与C语言相同,需要考虑短路的情况。例如:
print not 2, not []
print 2 or 3, 3 or 2
print [] or 3, [] or {}
print 2 and 3, 3 and 2
print [] and {}
print 3 and []
运算结果为:
False True
2 3
3 {}
3 2
[]
[]
4,while 语句(包括break和continue)与C语言中的类似,值得一提的是else,这个 else 只有在循环正常离开时才会执行(即没有碰到break语句)。
x = [1,2,3,4]
while x:
if x[0] == 3:
print x[0]
break
x = x[1:]
else:
print 'not found'
输出结果为:
3
5,Python中的pass是空占位语句。有时指的是“以后会填上”。
6,for语句时Python中一个通用的序列迭代器,可以遍历字符串、列表、元组、其它内置可迭代对象以及通过类创建的新对象。for语句跟while语句类似,也有else分支,在没有碰到break退出的情况下才会执行。下面是一些例子:
for x in [1,2,3,4]:
print x,
print ''
for s in 'mathboy':
print s,
print ''
T = [(1,2), (3,4), (5,6)]
for (a,b) in T:
print a,b
运算结果为:
1 2 3 4
m a t h b o y
1 2
3 4
5 6
7,对于可迭代对象,在迭代时Python会默认去调用next()方法来使对象前进到下一个结果,到达结尾时则会引发StopIteration异常。
8,读取文件最高效的方法是:
for line in open('myscript.py'):
print line
如果使用 for line in open('myscript.py').readlines() 则一次会把整个文件加载到内存中,如果内存不够大,会导致程序不能工作。
9,对于字典,可以这样迭代:
D = {'a':1, 'b':2, 'c':3}
for key in D:
print key,D[key]
结果为:
a 1
c 3
b 2
10,在循环语句中,常常使用range()函数,第一个参数表示起点,第二个参数表示终点(但不包括该终点),第三个参数表示步长。第一和第三个参数可以省略。例如:
print range(5)
print range(1,5)
print range(0,10,2)
输出结果为:
[0, 1, 2, 3, 4]
[1, 2, 3, 4]
[0, 2, 4, 6, 8]
11,使用range()的一个例子如下:
S = 'mathboylinlin'
for i in range(0,len(S),2):
print S[i],
结果为:
m t b y i l n
同样的结果可以通过更理想的方式得到:
S = 'mathboylinlin'
for x in S[::2]:
print x,
12,zip()函数常用来并行使用多个序列。例如:
L1 = [1,2,3,4]
L2 = [5,6,7,8]
print zip(L1,L2)
T1,T2,T3 = (1,2,3),(4,5,6),(7,8,9)
print zip(T1,T2,T3)
结果为:
[(1, 5), (2, 6), (3, 7), (4, 8)]
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
13,使用zip()函数还可以生成字典。例如:
keys = ['a','b','c']
vals = [1,2,3]
D = dict(zip(keys,vals))
print D
结果为:
{'a': 1, 'c': 3, 'b': 2}
14,复杂的列表解析有如:
[x + y for x in 'abc' for y in 'def']
了解这个表达式的一种方法就是将其写成缩进的语句:
res = []
for x in 'abc':
for y in 'def':
res += x + y