目录
57 字典
59 字典的创建
scores={'张三':100,'李四':98,'王五':105}
print(scores)
print(type(scores))
student=dict(name='jack',age=20)
print(student)
#空字典
d={}
print(d)
60 字典元素的获取
scores={'张三':100,'李四':98,'王五':105}
print(scores['张三'])
print(scores.get('张三'))
#print(scores['五六七'])
#KeyError: '五六七'
print(scores.get('五六七'))
#None
print(scores.get('五六七',99))#99是在查找’五六七‘所对的value不存在时,提供的一个默认值
#99
61 字典增删改
scores={'张三':100,'李四':98,'王五':105}
print('张三' in scores)
print('张三' not in scores)
del scores['张三']#删除指定的键值对
print(scores)
scores.clear()
print(scores)
# {'李四': 98, '王五': 105}
# {}
scores['陈六']=100
print(scores)
# {'陈六': 100}
62 获取字典试图
scores={'张三':100,'李四':98,'王五':105}
print(scores)
# {'张三': 100, '李四': 98, '王五': 105}
keys=scores.keys()
print(keys)
print(type(keys))
print(list(keys))#将所有的keys组成的视图组成列表
# dict_keys(['张三', '李四', '王五'])
# <class 'dict_keys'>
# ['张三', '李四', '王五']
values=scores.values()
print(values)
print(type(values))
print(list(values))#将所有的values组成的视图组成列表
# dict_values([100, 98, 105])
# <class 'dict_values'>
# [100, 98, 105]
items=scores.items()
print(items)
print(type(items))
print(list(items))#转换之后的列表元素是由元组组成的
# dict_items([('张三', 100), ('李四', 98), ('王五', 105)])
# <class 'dict_items'>
# [('张三', 100), ('李四', 98), ('王五', 105)]
63 字典元素遍历
scores={'张三':100,'李四':98,'王五':105}
for item in scores:
print(item,scores[item],scores.get(item))
64 字典的特点
65 字典生成式
item=['abc','def','ghi']
price=[1,2,3]
d={item:price for item,price in zip(item,price)}
print(d)
# {'abc': 1, 'def': 2, 'ghi': 3}
item=['abc','def','ghi','dsdf']
price=[1,2,3,4,5]
d={item:price for item,price in zip(item,price)}
print(d)
# {'abc': 1, 'def': 2, 'ghi': 3, 'dsdf': 4}
两个列表不相等时,压缩打包的时候依据短的列表来生成
66 元组
不可变的序列:字符串、元组
可变序列:列表、字典
67 元组的创建
如果元组中只有一个元素,逗号不能省
t1=('python','world',23)
print(t1)
print(id(t1))
print(type(t1))
# ('python', 'world', 23)
# 1882095097664
# <class 'tuple'>
t2=tuple(('python','world',25))
print(t2)
print(id(t2))
print(type(t2))
# ('python', 'world', 25)
# 1882095097856
# <class 'tuple'>
t3='python','world',23
print(t3)
print(id(t3))
print(type(t3))
# ('python', 'world', 23)
# 1882095097664
# <class 'tuple'>
t=('python',)
print(t)
print(type(t))
# ('python',)
# <class 'tuple'>
t=('python')
print(t)
print(type(t))
# python
# <class 'str'>
#空元组创建方式
t=()
t1=tuple()
68 为什么元组是不可变序列
t=(10,[20,30],9)
print(t)
# t[1]=100 TypeError: 'tuple' object does not support item assignment
t[1].append(100)
print(t)
# (10, [20, 30], 9)
# (10, [20, 30, 100], 9)
69 元组的遍历
t=tuple(('python','world',25))
#使用索引获取元组,容易越界
print(t[0])
print(t[1])
print(t[2])
#遍历元组获取元组,不需要知道元祖个数
for item in t:
print(item)
70 集合
集合中元素不允许重复;集合中元素无序
s={23,25,43,32,23,123,43,34,23}
print(s)
print(type(s))
# {32, 34, 23, 123, 25, 43}
# <class 'set'>
s=set(range(6))
print(s,type(s))
# {0, 1, 2, 3, 4, 5} <class 'set'>
print(set([3,4,5,6,5]))
# {3, 4, 5, 6}列表转集合
print(set((3,4,5,3,2,34,3,32,2)))
# {32, 34, 2, 3, 4, 5}元组转集合,集合中元素无序
print(set('PYTHON'))
# {'Y', 'H', 'P', 'O', 'N', 'T'} 字符串序列转集合
print(set({1,2,3,4,2,3,4,5,124}))
{1, 2, 3, 4, 5, 124}
#不能用花括号定义空集合
print(type({}),{})
print(type(set()),set())
# <class 'dict'> {}
# <class 'set'> set()
71 集合增删
s={10,20,30,40,50}
print(10 in s)
print(100 in s)
s.add(100)
print(s)
s.update({200,400,300})
print(s)
s.update([500,600])
print(s)
s.update((700,800))
print(s)
# {50, 20, 100, 40, 10, 30}
# {100, 40, 200, 10, 300, 400, 50, 20, 30}
# {100, 40, 200, 10, 300, 400, 50, 20, 500, 600, 30}
# {800, 100, 40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
s.remove(100)
print(s)
# s.remove(900) KeyError: 900
s.discard(900)
print(s)
s.pop()
print(s)
# s.pop(400) TypeError: set.pop() takes no arguments (1 given) 函数pop()
# {800, 40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
# {800, 40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
# {40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
s.clear()
print(s)
# set()
72 集合间的关系
s={10,20,30,40}
s1={20,10,40,30}
print(s1==s)
#True
s2={10,30}
s3={30,50}
print(s2.issubset(s))
print(s3.issubset(s))
# True
# False
print(s.issuperset(s2))
print(s.issuperset(s3))
# True
# False
s4={60,70,80}
print(s.isdisjoint(s1))
print(s.isdisjoint(s2))
print(s.isdisjoint(s4))
# False
# False
# True
73 集合的数据操作
#交集:intersection() 或 &
s1={10,20,30}
s2={23,30,20}
print(s1.intersection(s2))
print(s1 & s2)
# {20, 30}
# {20, 30}
#并集:union() 或 |
print(s1.union(s2))
print(s1 | s2)
# {20, 23, 10, 30}
# {20, 23, 10, 30}
#差集:difference() 或 -
s1={10,20,30,40}
s2={20,30,50}
print(s1.difference(s2))
print(s1-s2)
# {40, 10}
# {40, 10}
#对称差集:symmetric_difference() 或 ^
s1={10,20,30,40}
s2={20,30,50}
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
# {40, 10, 50}
# {40, 10, 50}
74 集合生成式
#列表生成式
lst=[i*i for i in range(6)]
print(lst,type(lst))
#集合生成式
s={i for i in range(6)}
print(s,type(s))
# [0, 1, 4, 9, 16, 25] <class 'list'>
# {0, 1, 2, 3, 4, 5} <class 'set'>
75 字符串
a='Python'
b='Python'
c='Python'
print('a:',a,id(a))
print('b:',b,id(b))
print('c:',c,id(c))
# a: Python 2834106576176
# b: Python 2834106576176
# c: Python 2834106576176
76 字符串查找
s='hello,hello'
print(s.index('lo'))#3
print(s.rindex('lo'))#9
print(s.find('lo'))#3
print(s.rfind('lo'))#9
#print(s.index('k'))ValueError: substring not found
print(s.find('k')) #-1
77 字符串大小写转换
转换之后,会产生一个新的字符串对象
s='hello,python'
print(s,id(s))
print(s.upper(),id(s.upper()))
# hello,python 2564162926064
# HELLO,PYTHON 2564162925936
a='HELLO,PYTHON'
print(a,id(a))
print(a.lower(),id(a.lower()))
# HELLO,PYTHON 2564162926448
# hello,python 2564162926512
print(a==s.upper())
print(a is s.upper())
# True
# False
#内容相同,地址不同
s1='asfJSEOFH'
print(s1.swapcase())
print(s1.capitalize())
s2='sdjf ddjo EJOSD CNDDScjd'
print(s2.title())
# ASFjseofh
# Asfjseofh
# Sdjf Ddjo Ejosd Cnddscjd
78 字符串内容对齐
宽度,指定填充符
s='hello,Python'
print(s.center(20,'*'))
# ****hello,Python****
print(s.ljust(20,'*'))
print(s.ljust(10,'*'))
print(s.ljust(20))
# hello,Python********
# hello,Python
# hello,Python
print(s.rjust(20,'*'))
print(s.rjust(20))
print(s.rjust(10))
# ********hello,Python
# hello,Python
# hello,Python
print(s.zfill(20))
print('-9010'.zfill(8))
# 00000000hello,Python
# -0009010
79 字符串的劈分
s='hello world python'
lst=s.split()
print(lst)
s1='hello|world|python'
print(s1.split())
print(s1.split(sep='|'))#让分隔符为竖线
print(s1.split(sep='|',maxsplit=1))#只分一次
# ['hello', 'world', 'python']
# ['hello|world|python']
# ['hello', 'world', 'python']
# ['hello', 'world|python']
s='hello world python'
lst=s.rsplit()
print(lst)
s1='hello|world|python'
print(s1.rsplit())
print(s1.rsplit(sep='|'))#让分隔符为竖线
print(s1.rsplit(sep='|',maxsplit=1)) #从右侧开始劈分,只分一次
# ['hello', 'world', 'python']
# ['hello|world|python']
# ['hello', 'world', 'python']
# ['hello|world', 'python']
80 字符串判断
s='hello,python'
print(s.isidentifier())
s='hello2341_python'#字母数字下划线
print(s.isidentifier())
# False
# True
s=' \n \t'
print(s.isspace())
# True
s='dsjfSDLFJ'
print(s.isalpha())
s='dsf3'
print(s.isalpha())
# True
# False
s='238509'
print(s.isdecimal())
s='九02347'
print(s.isdecimal())
# True
# False
s='32840四五十四'
print(s.isnumeric())
# True
s='sdjf324'
print(s.isalnum())
# True
81 字符串替换和合并
s='hello,python,python,python'
print(s.replace('python','c++'))
s='hello,python,python,python'
print(s.replace('python','c++',2))
# hello,c++,c++,c++
# hello,c++,c++,python
lst=['hello','java','python']
print('|'.join(lst))
print(''.join(lst))
# hello|java|python
# hellojavapython
t=('hello','java','python')
print('|'.join(t))
print(''.join(t))
# hello|java|python
# hellojavapython
print('*'.join('Python'))
# P*y*t*h*o*n
82 字符串比较
print('apple'>'app')
print('aanan'>'banan')
print(ord('a'),ord('b'))
print(chr(97),chr(98))
# True
# False
# 97 98
# a b
print(ord('孙'))
print(chr(23385))
# 23385
# 孙
==和is的区别:
==比较的是value
is比较的是id是否相等
83 字符串切片
切片[start:stop:step]
从start开始截到stop(不包含stop),步长为1(两个元素之间的间隔)
s='hello,Python'
s1=s[:5]#由于没有指定起始位置,从0开始切
s2=s[6:]#由于没有指定结束位置,切到字符串的最后一个元素
print(s1+'!'+s2)
# hello!Python
s='hello,Python'
print(s[1:5:1])
print(s[::2])
# ello
# hloPto
84 格式化字符串
name='张三'
age=20
print('我叫%s,今年%d岁' % (name,age))
# 我叫张三,今年20岁
print('我叫{0},今年{1}岁了'.format(name,age))
# 我叫张三,今年20岁了
print(f'我叫{name},今年{age}岁!')#字符串前加f代表格式化字符串
用%和{}来设置宽度和精度
print('%10d' % 99)#宽度
print('0123456789')
print('%.3f'%3.1415926)#保留小数
print('%10.3f'%3.1415926)
# 99
# 0123456789
# 3.142
# 3.142
print('{0:.3}'.format(3.1415926))#:.3表示一共是三位数
print('{0:.3f}'.format(3.1415926))#:.3f表示三位小数
print('{0:10.3f}'.format(3.1415926))#同时设置宽度和精度
# 3.14
# 3.142
# 3.142
85 字符串的编码与解码
s='天涯共此时'
print(s.encode(encoding='GBK'))#一个中文占两个字节
print(s.encode(encoding='UTF-8'))#一个中文占三个字节
# b'\xcc\xec\xd1\xc4\xb9\xb2\xb4\xcb\xca\xb1'
# b'\xe5\xa4\xa9\xe6\xb6\xaf\xe5\x85\xb1\xe6\xad\xa4\xe6\x97\xb6'
#解码
byte=b'\xcc\xec\xd1\xc4\xb9\xb2\xb4\xcb\xca\xb1'
print(byte.decode(encoding='GBK'))
byte=b'\xe5\xa4\xa9\xe6\xb6\xaf\xe5\x85\xb1\xe6\xad\xa4\xe6\x97\xb6'
print(byte.decode(encoding='UTF-8'))
# 天涯共此时
# 天涯共此时
86 函数
def calc(a,b):
c=a+b
return c
result=calc(10,20)
print(result)#30
87 函数的参数传递
88 参数传递的内存分析
在函数调用过程中,进行参数的传递,如果是不可变对象,在函数体内的修改不会影响实参的值
如果是可变对象,修改形参影响实参
不可变类型(数字,字符串,元组,不可变集合):不支持原处修改。
def fun(arg1,arg2):
print('arg1=',arg1)
print('arg2=',arg2)
arg1=100
arg2.append(10)
print('arg1=',arg1)
print('arg2=',arg2)
n1=11
n2=[22,33,44]
print('n1=',n1)
print('n2=',n2)
print('+++++++++++++')
fun(n1,n2)
print('n1=',n1)
print('n2=',n2)
# n1= 11
# n2= [22, 33, 44]
# +++++++++++++
# arg1= 11
# arg2= [22, 33, 44]
# arg1= 100
# arg2= [22, 33, 44, 10]
# n1= 11
# n2= [22, 33, 44, 10]
89 函数的返回值
def fun(num):
odd=[]
even=[]
for i in num:
if i%2:
odd.append(i)
else:
even.append(i)
return odd,even
print(fun([10,29,34,23,44,53,55]))
# ([29, 23, 53, 55], [10, 34, 44])
函数的返回值:
1.如果函数没有返回值(函数执行完毕后,不需要给调用出提供数据),return可以省略不写
2.函数的返回值,如果是1个,直接返回原值类型
3.函数的返回值,如果是多个,返回的结果为元组
def fun():
return 'ed','df','sdfa'
print(fun())
# ('ed', 'df', 'sdfa')
90 函数的参数定义 - 默认值参数
def fun(a,b=10):
print(a,b)
fun(100)
fun(20,30)
# 100 10
# 20 30
91 函数的参数定义 - 个数可变的未知参数
个数可变的位置参数,只能是一个
个数可变的关键字参数,只能是一个
既有个数可变的位置形参,也有个数可变的位置形参时,个数可变的位置形参要放在个数可变的关键字形参之前
def fun(*args):#可变的位置参数
print(args)
fun(10)
fun(60,20,30)
# (10,)
# (60, 20, 30)
def fun(**args):#可变的关键字形参
print(args)
fun(a=10)
fun(a=50,b=30,c=100)
# {'a': 10}
# {'a': 50, 'b': 30, 'c': 100}
92 参数总结
def fun(a,b,c):#形式参数
print('a=',a)
print('b=',b)
print('c=',c)
fun(10,20,30)#函数调用时的参数传递,称为位置实参传参
lst=[11,22,33]
fun(*lst) #在函数调用时,将列表中的每个元素都转换为位置实参传入
fun(a=100,b=200,c=300)#函数的调用,关键字实参
dic={'a':111,'b':222,'c':333}
fun(**dic)#在函数调用时,将字典的键值对都转换为关键字实参传入
# a= 10b= 20c= 30
# a= 11b= 22c= 33
# a= 100b= 200c= 300
# a= 111b= 222c= 333
def fun(a,b=10):#b是在函数的定义处,且进行了赋值,是默认值形参
print('a=',a)
print('b=',b)
def fun2(*args):#个数可变的位置形参
pass
def fun3(**args):#个数可变的关键字形参
pass
def fun4(a,b,*,c,d):#关键字形参:从*之后的参数,在函数调用时,只能采用关键字参数传递
print('a=',a)
print('b=',b)
print('c=',c)
print('d=',d)
fun4(10,20,c=30,d=40)#前两个参数位置实参,后两个参数关键字实参传递
# a= 10
# b= 20
# c= 30
# d= 40
93 变量的作用域
94 递归函数
def fac(n):
if n==1:
return 1
else:
res=n*fac(n-1)
return res
print(fac(6))
95 斐波那契数列
求斐波那契数列:
def fib(n):
if n==1:
return 1
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
print(fib(6))#第六位
#前六位
for i in range(1,7):
print(fib(i),end='\t')
# 8
# 1 1 2 3 5 8