python 条件、循环

来源:互联网 发布:u盘制作linux安装盘 编辑:程序博客网 时间:2024/06/03 21:51

学习笔记


import导入

import somemodule

from somemodule import somefunction 

from somemodule import somefunction ,anotherfunction ,yetanotherfunction

from somemodule import *

最后一个导入模块所有功能


as 为函数提供别名


序列解包

>>> x,y,z = 1,2,3>>> x,y = y,x>>> print(x,y,z)2 1 3

条件和条件语句

false None 0 "" () [] {} 都会被看作假


if condition:

elif condition:

else:

and = &&

or = ||

not = !

断言assert 判断condition错误报错


range()类似于分片,包含下限不包含上限

xrange()一次只创建一个数,当需要迭代一个巨大的序列时xrange更高效

在python3中xrange改名为range


迭代工具

并行迭代

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


zip函数可以把两个序列压缩在一起,py2返回一个元祖的列表,py3返回一个对象

编号迭代

index = 0for string in strings:    if 'xxx' in string:    strings[index] = '[censored]'index += 1
使用内建的enumerate函数
for index, string in enumerate(strings):   if 'xxx' in string:        strings[index] = '[censored]'


翻转和排序迭代

reversed和sorted函数和列表的reverse和sort方法类似,返回翻转或排序后的版本。


列表推导式,轻量级循环

>>> [x*x for x in range(10) if x % 3 == 0][0, 9, 36, 81]

 exec在py2中为语句,在py3中和execfile()整合到exec()函数。无返回值。

x = 10expr = """z = 30sum = x + y + zprint(sum)"""def func():    y = 20    exec(expr)    exec(expr, {'x': 1, 'y': 2})    exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})    func()
结果:

60

33

34

eval函数类似于exec,计算一个表达式并返回结果值。