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,计算一个表达式并返回结果值。
阅读全文
0 0
- Python:循环、条件判断
- Python:条件和循环
- python条件判断、循环
- python 条件、循环
- python 条件,循环
- python的循环条件
- python条件、循环、终止
- python条件与循环
- Python 条件和循环
- python中的条件和循环
- python条件及循环语句
- python 条件判断和循环
- python 条件判断与循环
- Python学习笔记:条件、循环
- Python(条件判断和循环)
- python之条件、循环语句
- python条件判断与循环
- Python-条件判断和循环
- AJAX
- sql server 存储过程
- 详解C#中的反射
- CDOJ1597-线段树好题(2017 UESTC Training for Data Structures C)
- Titanic问题学习
- python 条件、循环
- 阶乘数
- k-近邻算法(详细代码注释与调参性能分析)
- linux rpm安装错误Failed dependencie解决
- Spring Cloud TIps
- 深刻理解计算机补码的含义
- MLP-多层感知机的原理及Matlab实现
- android xutils 注解 include 标签
- [牛客网,剑指offer,python] 斐波那契数列