您的位置:首页 > 编程语言 > Python开发

<PY><core python programming笔记>C8 条件与循环

2014-05-05 13:29 686 查看


C8 条件与循环

8.1 if

#Python的缩进 可以避免C语言中的else悬挂

if expression:

if inner_expression:

inner_if_suite

elif expression2:

suite2

else:

suite3

#三元操作符简化if语句

smaller =x if x<y else y

8.5 while

8.5.1

while expre:

suite

8.5.2 计数循环

count =0

while (count<9):

suite

count+=1

8.5.3 无限循环

while True:

suite

8.5.4 状态控制循环

status =1

while status:

suite

if expre:

status =0 #也可以用break

else:

pass

8.5.5while else 或者 for else

while expre:

suite1

else:

suite2

#这里else在循环结束后执行 可以被while中的break跳过

8.6 for

for iter_var in iterable1[,iterable2]:

suite

#可以是 aString aList enumerate()

namelist=['Ben','Yen','Wen']

for i,eachLee in enumerate():

print "%d %s Lee"%(i+1,eachLee)

#可以是可迭代器类型

#可以是range(start or start=0,end,step=1) #start<=k<end

#xrange() 只在for内创建内存 适用大范围列表和高性能

8.7break

跳出上层循环 一般在if中判断后跳出

8.8continue

取消当前一次迭代 若符合条件则进入下一次迭代

8.9pass

不做任何事 仅仅是语法需要

8.11迭代器和iter()函数

通常是按照索引值进行迭代的 但设计了迭代器可以迭代一些有序列行为的的对象

列入字典的键 一个文件的行

迭代器:提供可扩展的迭代器接口

对列表带来了性能上的增强

在字典迭代中性能提升

创建真正的迭代接口,而不是原来的随机对象访问

与所有的已经存在的用户定义的类以及扩展的模拟序列和映射的对象向后兼容

迭代非序列集合时(字典或文件),可以创建更简洁的可读代码

8.11.3如何迭代

next() enumerate() any() all()

8.11.4使用迭代器

1.序列

>>>myTuple=(123,'xyz',45.67)

>>>i=iter(myTuple)

>>>i.next()

123

>>>i.next()

'xyz'

#直到无obj而迭代出错

2.字典

for eachLegend in lengends:

print legends[eachLengend]

3.文件

for eachLine in myFile:

print eachLine

#可变对象在迭代时不要修改, 因为迭代器是实际绑定的,修改了就不能再执行了

8.12列表解析(useful)

>>>[x**2 for x in range(6)]

[0,1,4,9,16,25]

>>>[x for x in range(6) if x%2] #加条件

[1,3,5]

>>>[(x+1,y+1) for x in range(3) for y in range(2)] #矩阵

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

>>>len([word for line in f for word in line.split()]) #统计非空白字符数

>>>sum([len(word) for line in f for word in line.split()]) #统计总字长

8.13生成器表达式(列表解析的一个扩展,在内存上更有效,就是把方括号改圆括号)

>>>sum(len(word) for line in f for word in line.split()) #统计总字长

>>>((i,j) for i in rows for j in cols )

>>>longest=max(len(x.strip()) for x in f) #得到文件最长行

#注意,文件资源要及时释放

8.14相关模块

itertools

习题:

8-9:

def fibonacci(n):

fi=[0]

for i in range(n):

fi.append(i)

return fi

print fibonacci(5)

8-13:

#coding=utf-8

import time

def compare():

strtime=time.clock()

alist=range(1000000)

#for i in range(len(alist)):

# print alist[i],

for i in alist:

print i,

endtime=time.clock()

print "运行时间: ",(endtime-strtime)

compare()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: