5.5.1while循环

x=1
while x<=100:
print x
x+=1

确保用户输入了名字:

name=""
while not name:
name=raw_input('please enter your name:')
print 'hello,%s!'%name

5.5.2for循环

while语句非常灵活。它可以用来在任何条件为真的情况下重复执行一个代码块。一般情况下这样就够用了,但是有些时候还得量体裁衣。比如要为一个集合(序列和其他可迭代对象)的每个元素都执行一个代码块。这个时候可以使用for语句:

words=['a','b','c','d']
for word in words:
print word

5.5.3循环遍历字典元素

一个简单的for语句就能循环字典的所有键,就像处理序列一样

d={'x':1,'y':2,'z':3}
for key in d:
print key,'corresponds to',d[key]

注意:字典元素的顺序通常是没有定义的。换句话说,迭代的时候,字典中的健和值都能保证被处理,但是处理顺序不确定。如果顺序很重要的话,可以将键值保存在单独的列表中,例如在迭代前进行排序。

5.5.4一些迭代工具

1.并行迭代

程序可以同时迭代两个序列。

names=['anne','beth','george','damon']
ages=[12,45,32,102]
for i in range(len(names)):
print names[1],'is',ages[i],'years old'

内建的zip函数可以用来进行并行迭代,可以把两个序列“压缩”在一起,然后返回一个元组的列表:

>>> zip(names,ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]

循环中解包元组:

>>> for name,age in zip(names,ages):

    print name,'is',age,'years old'

anne is 12 years old

beth is 45 years old

george is 32 years old

damon is 102 years old

zip函数也可以作用于任意多的序列。关于它很重要的一点是zip可以应付不等长的序列:当最短的序列“用完”的时候就会停止:

>>> zip(range(5),xrange(100000000))

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

2.编号迭代

有些时候想要迭代序列中的对象,同时还要获取当前对象的索引。例如,在一个字符串列表中替换所有包含’XXX’的子字符串:\

index=0

for string in strings:

    if 'xxx' in strings:

    strings[index]='[censored'

index+=1

另一种方法是使用内建的enumerate函数:

3.翻转和排序迭代

两个有用的函数:reversed和sorted:它们同列表的reverse和sort (sorted和sort使用同样的参数)方法类似,但作用于任何序列或可迭代对象上,不是原地修改对象,而是返回翻转或排序后的版本:

>>> sorted([4,3,5,8,1])

[1, 3, 4, 5, 8]

>>> sorted('hell,world!')

['!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'r', 'w']

>>> list(reversed('hello,world'))

['d', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']

>>> ''.join(reversed('hello,world!'))

'!dlrow,olleh'

5.5.5跳出循环

1. break

结束(跳出)循环可以使用break语句。

from math import sqrt

for n in range(99,0,-1):

    root=sqrt(n)

    if root ==int(root):

        print n

        break

2. continue

continue会让当前的迭代结束,“跳”到下一轮循环的开始。它最基本的意思是“跳过剩余的循环体,但是不结束循环”。当循环体很大而且很复杂的时候,这会很有用,有些时候因为一些原因可能会跳过它—这个时候可以使用continue语句:

for x in seq:

if condition1: continue

if condition2: continue

if condition3: continue

do_something()

da_ something_ else()

do_ another_thing()

etc()

很多时候,只要使用if语句就可以了:

for x in seq:

if not (condition1 or condition2 or condition3)

do_something()

do_something_else()

do_another_thing()

etc()

3.while True/break习语

while True:

    word=raw_input('please enter a word:')

    if not word:break

    print 'the word was '+word

while True的部分实现了一个永远不会自己停止的循环。但是在循环内部的if语句中加入条件可以的,在条件满足时调用break语句。这样一来就可以在循环内部任何地方而不是只在开头(像普通的while循环一样)终止循环。if/break语句自然地将循环分为两部分:第1部分负责初始化(在普通的while循环中,这部分需要重复),第2部分则在循环条件为真的情况下使用第1部分内初始化好的数据。

5.5.6循环中的else子句

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"

5.6列表推导式——轻量级循环

列表推导式(list comprehension)是利用其他列表创建新列表(类似于数学术语中的集合推导式)的一种方法。它的工作方式类似于for循环:

>>> [x*x for x in range(10)]

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

可以增加更多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)

5.7三人行 :pass, del和exec

5.7.1 pass

它可以在的代码中做占位符使用。比如程序需要一个jf语句,然后进行测试,但是缺少其中一个语句块的代码,考虑下面的情况:

if name=='ralph':
print 'welcome!'
elif name=='enid':
pass
elif name=='bill':
print 'access'

5.7.2使用del删除

>>> scoundrel={'age':42,'first name':'robin','last name':'of locksley'}
>>> robin=scoundrel
>>> scoundrel
{'last name': 'of locksley', 'first name': 'robin', 'age': 42}
>>> robin
{'last name': 'of locksley', 'first name': 'robin', 'age': 42}
>>> coundrel=None
>>> robin
{'last name': 'of locksley', 'first name': 'robin', 'age': 42}
>>> robin=None

首先,robin和scoundrel都被绑定到同一个字典上。所以当设置scoundrel为None的时候,字典通过robin还是可用的。但是当我把robin也设置为None的时候,字典就“漂”在内存里面了,没有任何名字绑定到它上面。没有办法获取和使用它,所以Python解释器(以其无穷的智慧)直接删除了那个字典(这种行为被称为垃圾收集)。

>>> x=["hello","world"]
>>> y=x
>>> y[1]="python"
>>> x
['hello', 'python']
>>> del x
>>> y
['hello', 'python']
>>> x
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'x' is not defined

5.7.3 使用exec和eval执行和求值字符串

1 .exec
执行一个字符串的语句是exec:

>>> exec "print 'hello,world!'"
hello,world!
>>> from math import sqrt
>>> exec "sqrt=1"
>>> sqrt(4)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'int' object is not callable

exec语句最有用的地方在于可以动态地创建代码字符串。如果字符串是从其他地方获得的—很有可能是用户—那么几乎不能确定其中到底包含什么代码。所以为了安全起见,可以增加一个字典,起到命名空间的作用。

可以通过增加in<scope>来实现,其中的<seope>就是起到放置代码字符串命名空间作用的字典。

>>> from math import sqrt
>>> scope={}
>>> exec "sqrt=1" in scope
>>> sqrt(4)
2.0
>>> scope['sqrt']
1

可以看到,潜在的破坏性代码并不会覆盖sqrt函数,原来的函数能正常工作,而通过exec赋值的变量sqrt只在它的作用域内有效。注意,如果需要将scope打印出来的话,会看到其中包含很多东西,因为内建的_builtins_字典自动包含所有的内建函数和值:

>>> len(scope)
2
>>> scope.keys()
['__builtins__', 'sqrt']

2.eval

eval(用于“求值”)是类似于exec的内建函数。exec语句会执行一系列Python语句,而eval会计算Python表达式(以字符串形式书写),并且返回结果值,(exec语句并不返回任何对象,因为它本身就是语句)。例如,可以使用下面的代码创建一个Python计算器:

>>> eval(raw_input("enter an arthmetric expression:"))
enter an arthmetric expression: 6+18*2
42

5.8 小结  

本章的新函数

chr(n)   当传入序号n时,返回n所代表的包含一个字符的字符串,(0, n< 256)
eval(source[,globals[,locals]])  将字符申作为表达式计算,并且返回值
enumerate(seq) 产生用于迭代的(索引,值)对
ord(c)  返回单字符字符串的int值
range([start,]stop[,step])  创建整数的列表
reversed(seq)  产生seq中值的反向版本,用于迭代
sorted(seq[,cmp][,key][,reverse])  返回seq中值排序后的列表
xrange([start,]stop[,step])  创造xrange对象用于迭代
zip(seq1,_eq2.…)  创造用于并行迭代的新序列

最新文章

  1. 2013最新版Subversion 1.7.10 for Windows x86 + Apache 2.4.4 x64 安装配置教程+错误解决方案
  2. TextView里限制输入字数的方法
  3. Web前端开发规范文档(google规范)
  4. cf306 C. Divisibility by Eight(数学推导)
  5. Qt 获取Mac地址
  6. 在Salesforce中通过 Debug Log 方式 跟踪逻辑流程
  7. node js 模块分类
  8. js实现倒计时及时间对象
  9. UWP好文
  10. Activiti 流程实例、任务、执行对象及相关的表
  11. using-ef-code-first-with-an-existing-database
  12. Android:View中的performClick()触发条件
  13. 理解extern char s[100]与extern char *s
  14. Nutch之简介与安装
  15. C--运算符,表达式和语句实例
  16. Caused by: java.lang.NoClassDefFoundError: org/springframework/web/context/WebApplicationContext
  17. discuz全新安装升级,导入旧数据过程,顺便gbk转utf8
  18. Linux主机操作系统加固规范
  19. 从一些代码方法中,去学习C#委托
  20. 8,EasyNetQ-多态发布和订阅

热门文章

  1. sql server filter table name
  2. 3种方法判断手机浏览器跳转WAP手机网站
  3. eclipse、idea切换大小写的快捷键
  4. fullcalendar小结
  5. 廖雪峰python3练习题三
  6. Table View Programming Guide for iOS---(四)---Navigating a Data Hierarchy with Table Views
  7. MySQL暴错注入方法整理
  8. JVM的参数详解
  9. ASP.NET Core中间件计算Http请求时间
  10. hdu1272 小希的迷宫 基础并查集