6、循环
(1) while语句
x = 1
while x <= 10:
print x
x += 1
(2) for语句
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
print number
l range()函数:返回指定返回的数值:
>>> range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l 通常从0开始,则可以省略开始限制:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l 也可以不从0开始,下面输出1到100:
for number in range(1,101):
print number
l 如果遍历的Sequence很大,可以使用xrange()函数,效率要高
(3) 遍历Dictionary
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print key, 'corresponds to', d[key]
l 使用Sequence拆分:
for key, value in d.items():
print key, 'corresponds to', value
l 为了更高效的遍历,可以使用iterkeys()、itervalues()或iteritems(),在后面讲述
(4) 遍历工具之zip()
l 并行遍历的例子:
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
for i in range(len(names)):
print names[i], 'is', ages[i], 'years old'
l zip()函数:合并多个Sequence,返回包含Tuple的List
>>> zip(names, ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
l 使用zip()函数的例子:
for name, age in zip(names, ages):
print name, 'is', age, 'years old'
l 如果合并的Sequence长度不同,取最短的:
>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
(5) 遍历工具之enumerate()
l 遍历Sequence中元素时,访问index值的例子:
for string in strings:
if 'xxx' in string:
index = strings.index(string)
strings[index] = '[censored]'
l enumerate()函数:允许使用index/value对进行遍历:
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
(6) 跳出循环
l break语句
l continue语句
l else子句:只有在break语句没有执行时,才会执行
from math import sqrt
for n in range(99, 81, -1):
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"
7、List包含:一种创建List的方法,类似循环
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
l 使用if:
>>> [x*x for x in range(10) if x % 3 == 0]
[0, 9, 36, 81]
l 使用多个for:
>>> [(x, y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
l 同样可以使用if:
>>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
['chris+clarice', ' arnold + alice ', 'bob+bernice']
l 上面例子的更好方案:
girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
letterGirls = {}
for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
8、其它语句
(1) pass语句
l Python不允许有空的语句块,这是可以使用pass语句来解决这个问题,pass语句不做什么操作
(2) del语句
l 通常,Python会删除不再使用的名字,但也可以使用del语句显式删除:
>>> x=1
>>> del x
>>> x
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'x' is not defined
l 要注意删除对象的引用,并不会删除对象本身:
>>> x = ["Hello", "world"]
>>> y = x
>>> del x
>>> y
['Hello', 'world']
(3) exec和eval语句
l exec:执行String包含的一系列Python语句
>>> exec "print 'Hello, world!'"
Hello, world!
l 名字冲突的例子:
>>> from math import sqrt
>>> sqrt(4)
2.0
>>> sqrt = 1
>>> sqrt(4)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: 'int' object is not callable
l 解决方法:使用namespace
>>> from math import sqrt
>>> scope = {}
>>> exec 'sqrt = 1' in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1
l eval:计算Python表达式,返回结果
>>> eval(raw_input("Enter an arithmetic expression: "))
Enter an arithmetic expression: 6 + 18 * 2
42
l 使用namespace:
>>> scope = {}
>>> scope['x'] = 2
>>> scope['y'] = 3
>>> eval('x * y', scope)
6