本笔记未加整体,占供自己查看
目录
一、流程控制
if else 条件语句
True False
if <条件>:
statement
else :
statement
if:
statement
elif:
statement
else:
statement
循环
for循环
for iterating_var in sequence:
statement
例如:
for x in 'abcd' #及循环4次
range 函数
range(100) 左闭右开
[0,1,2,...,99]
for x in range(100) #打印100次
range(1,11) 取1~10
range(start,end,step) //增加步长
遍历序列及字典
遍历序列
for x in 'hello'
print x
s="hello"
for x in range(len(s))
pritn(s[x])
遍历字典
d={1:111,2:222,5:555}
for x in d
print x #输出的是key
print d[x] #输出的是value
d.items() 返回字典中所有的键值对
for k ,v in d.items() //遍历字典的key
print k
print v
else "ending"
import time
for x in [1,2,3]
print x
time.sleep(1) //停止一秒
else
"ending"
exit() 退出程序
while循环
while:
else:
print "ending....."
二、函数
定义
def 函数名(参数列表):
#可以没有函数体
x=1
print "I get a:",x
#coding:utf8 //中文编码
默认参数
def fun(x,y="奶油")
//something
fun(y='巧克力')
变量作用域
global 强制声明为全局变量
def fun():
global y=1;
print y
传参 -->元组和字典
def fun(x):
print x
fun([2,3,4,5])
def fun(x,y)
print x,y
t=('a','b') //元组
fun(*t)
则x='a' ,y='b'
def fun(name="name",age=0)
print "name: %s",name
print "age : %d",age
d={'age':30,name="milo"} //字典
fun(**d)
处理多余实参
def fun(x,*args): #元组
print x
print args
f(1,2,3,4)
则args=(2,3,4)
def fun(x,*args,**kwargs):
print x
print args
print kwargs
fun(1,2,3,4,x=10,x=2,334,z=4)
#x即等于1又等于10 ,是有问题的
有对应关系的放入字典中
Lambda表达式 :匿名函数
def fun(x,y)
return x*y
g=lambda x,y:
x*y
#x,y是参数,: 后面是返回值
内置函数reduce
l=[1,2,3,4,5]
def f(x,y):
return x*y;
reduce(f,l)
>>>120 即5!
函数可以换成f=lambda x,y:x*y
或者可以写成reduce(lambda x,y:x*y,l)
switch python中没有switch
但是可以通过字典实现
from __future__ import division
引出该模块 5/2则=2.5
operator={"+":jia,"-":jian,"*":cheng,"/":chu}
print operator["+"](1,2)
def f(x,o,y):
print operator.get(o)(x,y)
内置函数
abs() 求绝对值
max() 求最大值
min() 求最小值
len()
divmod(5,2) -> (2,1) 求(商,模)
pow(x,y[,z]) ->(x**y) [% z]
round() 返回浮点值round(12) ->12.0
callable(函数) 检查函数是否被定义
isinstance(l,list) ->True 判断对象属于哪种类型
cmp() 比较两个对象值是否相等
range()
xrange()
类型转换
type()
int()
long()
str()
list()
float()
tuple()
complex()
进制转换
oct()
string函数
str.capitalize()
将str首字母小写转化成大写
str.replace() 替换
s='hello world'
s.replace("hello",'good')
s->'good world'
ss='123123123'
ss.replace('1','x')
ss->'x23x23x23'
ss.replace('1','x',2)
ss->'x23x23123'
str.split 切割 str.splite(''[,count])
ip='192,168,1,123'
ip.split('.')
-->['192','168','1','123']
ip.split('.',1)
-->['192','168.1.123']
import string 导入模块
string.replace(str,old,new[,count])
对序列的内置函数
filter() 保留序列中通过函数返回True的元素
中文意思:过滤
def f(x):
if x>5:
return True
l=range(10)
filter(f,l) //过滤,保留l中大于5的数
但原来的l不变
zip() 并行遍历
name=['milo',zou','tom']
age=[20,30,40]
tel=['133','156','189']
zip(name,age,tel)
[('milo',20,'133'),('zou',30,'156'),()]
map()
map(None,name,age,tel)
这个上面的zip一样
而
test=[1,2]
zip(name,age,tel,test)
[(...),(...)]
map(Node,name,sge,tel,test)
[(...),(...),(Node...)]
a=[1,3,5]
b=[2,4,6]
让a和b两两元素相乘
def mf(x,y):
return x*y
map(mf,a,b)
[2,12,30]
reduce() 不需要递归,不需要遍历
用reduce作阶乘
def f(x,y):
return x*y
l=range(1,101)
reduce(f,l)
reduce(lambda x,y:x+y, [1,2,3,4])
as (((1+2)+3)+4)