1、元组
#元组tuple,与列表有很多类似。区别主要是元组中的元素是不可改变的;它的定义使用(),而不是[ ]
tuple1=(1,2,3,4,5,6)
print(tuple1[2])
tuple2=('123','abc','pht',123,456)
tuple2=tuple2[:2]+('哈哈',)+tuple2[2:]#元组的插入,哈哈 的后面一定要加, 因为,才是元组的“本体”,才表示它是一个元组
print(tuple2)
#-------------------------
temp='i am years old' #字符串的插入,与元组类似
temp=temp[:4]+'20'+temp[4:]
print(temp)
temp='i am years old' #如果split()不设置参数,则默认从空格分割
temp=temp.split()
print(temp)
#------------------字符串格式化format-------------
temp='{0} old {1} {2}'.format('how','are','you') #花括号表示replacement字段,设置位置参数用来替换
print(temp)
temp='{0} old {haha} {emmm}'.format('how',haha='are',emmm='you')#可以综合位置参数与关键字参数,但位置参数放在关键字参数之前
print(temp)
temp='{0:.1f}{1}'.format(1.2768,'KB') #{0:.1f}:将0代表的数字取小数点后一位小数,四舍五入
print(temp)
#-------------list函数:列表-------------------------------
a=list()
print(a) #生成一个空列表
b='how are you'
b=list(b)
print(b) # 输出:['h', 'o', 'w', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u']
c=(1,1,2,3,5,8,13,21,34) #c为一个元组。斐波那契数列
c=list(c)
print(c) #把一个元组变成一个列表,输出:[1, 1, 2, 3, 5, 8, 13, 21, 34]
#--------------tuple函数:把一个可迭代对象转换为元组-----------------------
#把其他形式转换为元组,与list类似,具体略过
#len() str()
Max=max(b) #max与min的参数中必须是同一类型,如:不能有字符型又有整型
Min=min(b)
print(Min) #返回空格
print(Max) #输出为y,ascii码的最大值
s=sum(c) #不能是字符型的
print(s) #88
syz=sum(c,10) #10为可选参数,加在后面
print(syz) #98
d=[45,12,3,69,88,5,100]
n=sorted(d) #从小到大排序
print(n,d) #d的元素顺序不做改变,sorted,以及下面的reversed都只是拷贝。而list.sort()等则不同
e=reversed(d)
print(e) #返回迭代器对象? <list_reverseiterator object at 0x0000009B1250EF48>
print(list(reversed(d))) #强制转换为list,翻转:[100, 5, 88, 69, 3, 12, 45]
print(d) #[45, 12, 3, 69, 88, 5, 100]
f=enumerate(d) #返回包含index值和item 值的元组,并枚举
print(f) #,返回一个对象,<enumerate object at 0x000000D4C47D5B88>
print(list(enumerate(d))) #[(0, 45), (1, 12), (2, 3), (3, 69), (4, 88), (5, 5), (6, 100)]
a=[1,2,3,4,5,7]
b=[2,5,7,8]
print(list(zip(a,b))) #zip返回各个参数的序列组成的元组,并用list转换,最后输出:[(1, 2), (2, 5), (3, 7), (4, 8)]
2、函数的基本操作
def Afunction(): #定义函数
print('hello world')
Afunction() #往上寻找,并调用函数
def Bfunction(name):
'加油的函数' #这是一个函数文档
print(name+'加油')
Bfunction('pht') #pht必须为字符串型的,与加油保持一致
print(Bfunction.__doc__) #打印出函数文档,双下划线
def add_(a,b):
c=a+b #c为函数中的局部变量
return c
print(add_(3,2))
# print(c) #这里会报错,因为c为局部变量,函数外无法访问
#关键字参数
def saysome(name,words):
print(name+words)
saysome(words='hahaha',name='pht') #当参数太多时,可以使用关键字参数,防止参数顺序出错
def hhhh(*a): #加*表示收集参数(可变参数)
print('a的长度:',len(a))
print(a[0])
hhhh(354,657,789,'hahaaha')
#函数的闭包.................
#lambda关键字创建匿名函数;过滤器filter;以及map()
def abc(x):
return x**2 #等价于下面的匿名函数
a=lambda x:x**2 # lambda 函数参数:函数返回值,它返回一个函数对象a
print(a(3))
print(list(filter(None,[1,0,True,False])))#filter有两个参数,1、funcion或者none类型,2、筛选对象(可迭代),返回True的对象
#用过滤器返回0-9中的奇数
print(list(filter(lambda x:x%2,range(10)))) #lambda构建了匿名函数,属于function类型
#map函数,有两个参数。1、function 2、一个序列。它可以将序列的数代入函数中,并返回一个序列
print(list(map(lambda x:x*5,range(15))))
3、递归:
def digui(n):
if n==1:
return 1
else:
return n*digui(n-1)
print(digui(5))