python学习
字符串
基本知识
转义符
print('hello\nyou')
输出:
hello
you
若在‘str'前加r:可以直接显示原始字符串,不进行转义。
print(r'hello\nbaby')
输出:
hello\nbaby
字符串的常见操作
1.isalnum() 若字符串至少有一个字符且所以字符都是字母或数字则true,否则false
print('shh45'.isalnum())
输出True‘
print(')('.isalnum())
输出False
2.isalpha() 若字符串至少有一个字符且所以字符都是字母则true,否则false
3,isdigit() 若字符串只包含数字则True,否则False,isnumeric()类似,但是在汉字数字,罗马数字情况下略有不同。
4.join(seq) 以指定字符串作为分隔符,将seq中所有元素(的字符串表示)合并为一个新的字符串。
print(' and '.join(['Lihua', 'Zhangsan','Lisi']))
输出:
Lihua and Zhangsan and Lisi
5.len(str) 返回字符串长度
6.lstrip() 去除左边的空格,rstrip() 去除右边的空格,strip() 去除字符串所有的空格。
print(' 2 7288hhduf'.lstrip())
输出:
2 7288hhduf
7.split(str=' ',num=string.count(str)) num=string.count(str) 以str为分隔符截取字符串,如果num有指定值,则仅截取num+1个字符串
print('Lihua and Zhangsan and Lisi'.split(' and ', 1))
输出:
['Lihua', 'Zhangsan and Lisi']
8.encode(encoding='UTF-8',error='strict') 以encoding指定的编码格式编码字符串,如果出错则默认报一个ValueError的异常,除非errors指定的是'ignore'或'replace'
列表
基本知识
写在[],元素用逗号分割,可变,元素可重复,有序。
namelist = ['Alla', 'Mara', 'John']
for name in namelist:
print(name)
name无所谓,也可以写成i,x等等。输出:
Alla
Mara
John
也可
namelist = ['Alla', 'Mara', 'John'];i=0
while i < len(namelist):
print(namelist[i])
i = i+1
输出同上。
列表常用操作
访问切片遍历
通过索引直接访问:
print(list1[1])
使用list[ : : ]切片:
list1 = [1,5,6,'f','g',[2,'f']]
print(list1[1:6:2])
输出:
[5, 'f', [2, 'f']]
遍历类似字符串,for i in list1:
增删改查
增
1.append() 在末尾增加元素。
list1 = [1,5,6,'f','g']
list1.append(['aba',4]) #将列表当做元素追加
print(list1)
输出:
[1, 5, 6, 'f', 'g', ['aba', 4]]
注意,append是直接修改原列表。
2.extend() 扩展列表。
list1 = [1,5,6,'f','g']
list1.extend(['aba',4])
print(list1)
输出:
[1, 5, 6, 'f', 'g', 'aba', 4]
3.insert() 在指定索引处插入新增元素。
list1 = [1,5,6,'f','g']
list1.insert(2, ['aba',5]) #在2索引处插入元素
print(list1)
输出:
[1, 5, ['aba', 5], 6, 'f', 'g']
删
1.del list [index] 删除指定索引的元素
list1 = [1,5,6,'f','g']
del list1[2] #删除索引2的元素
print(list1)
输出:
[1, 5, 'f', 'g']
2.pop(index) 弹出末尾指定索引元素,若无索引则默认弹出最后一个。
list1 = [1,5,6,'f','g']
list1.pop(2)
print(list1)
输出:
[1, 5, 'f', 'g']
3.remove() 移除指定元素(一般用在不知道索引时)
list1 = [1,5,6,'f','g']
list1.remove(5)
print(list1)
输出:
[1, 6, 'f', 'g']
注意,若要求删除的元素有重复,则只删除索引最前的一个
list1 = [1,5,6,'f','g',5]
list1.remove(5)
print(list1)
输出:
[1, 6, 'f', 'g', 5]
改
直接通过索引修改。
list1 = [1,5,6,'f','g',5]
list1[1]='五'
print(list1)
输出:
[1, '五', 6, 'f', 'g', 5]
查
主要是看元素存不存在。直接用if element in list:或not in
查找
1.list.index(ele,start,end) 看元素是否出现在给定的索引值之间。区间左闭右开(注意,一般来说区间是左闭右开,但randint()是左闭右闭)。若出现则返回对应元素的索引值,否则输出ValueError: ele is not in list。
若区间内待查找的元素有重复,则只返回最前面的元素索引。
list1 = [1,5,6,5,'f','g',5]
print(list1.index(5,1,5))
输出:1
2.list.count(ele) 查找整个列表内指定元素出现次数。
list1 = [1,5,6,5,'f','g',5]
print(list1.count(5))
输出:3
排序
1.list.reverse() 将列表所以元素顺序反转。
list1 = [1,5,6,5,'f','g',5]
list1.reverse()
print(list1)
输出:
[5, 'g', 'f', 5, 6, 5, 1]
2.list.sort() 将列表中元素升序排列,要求元素要么均为整数或浮点数,要么全为字符串。
list1 = [1,5,6,5.3,5]
list1.sort()
print(list1)
输出:
[1, 5, 5, 5.3, 6]
list1 = [1,5,6,5.3,5]
list1.sort(reverse=True) #降序排列
print(list1)
输出:
[6, 5.3, 5, 5, 1]
字符串的排列按编码对应的值,但若字符串长度不同则规则较复杂。
list1 = ['2','t','你是','你','ab']
list1.sort(reverse=True)
print(list1)
输出:
['你是', '你', 't', 'ab', '2']
嵌套
列表元素可以为列表,套娃。访问时类似二元数组。
list1 = [['1','b','c'],['你','数','傻逼']]
print(list1[1])
print(list1[1][1])
输出:
['你', '数', '傻逼']
数
例题作业
例1 三个办公室分八个老师。
import random
offices = [[],[],[]]#三个办公室
teachers = ['A','B','C','D','E','F','G','H']#八个老师
for name in teachers:
index = random.randint(0, 2)
offices[index].append(name)#给每个办公室随机分配老师
i = 1
for office in offices:
print('办公室{}的老师人数为{}'.format(i,len(office)))
print('老师为:',end='')
for name in office:
print('{}'.format(name),end='\t')
i += 1
print('\n')
输出:
办公室1的老师人数为4
老师为:B E F H
办公室2的老师人数为3
老师为:A D G
办公室3的老师人数为1
老师为:C
作业:
products = [['iphone',6888],['MacPro',14800],['xiaomi6',2499],['Coffee',31],['Book',60],['Nike',699]]
index = [0,1,2,3,4,5]
print('-'*6,'商品列表','-'*6)
for i in index:
print('{} {} {}'.format(i,products[i][0],products[i][1]))
goods = []
a = input('您想要买什么:')
while a.isnumeric()==True and int(a) in index:
goods.append(products[int(a)][0])
a = input('您想要买什么:')
if a =='q':
print('你要购买的商品为:',end='')
for i in goods:
print(i,end='\t')
else:
print('不存在对应编号的商品')
输出:
------ 商品列表 ------
0 iphone 6888
1 MacPro 14800
2 xiaomi6 2499
3 Coffee 31
4 Book 60
5 Nike 699
您想要买什么:2
您想要买什么:3
您想要买什么:4
您想要买什么:q
你要购买的商品为:xiaomi6 Coffee Book
答案:
products = [['iphone',6888],['MacPro',14800],['xiaomi6',2499],['Coffee',31],['Book',60],['Nike',699]]
i = 0
print('-'*6,'商品列表','-'*6)
for item in products:
print(str(i)+'\t'+item[0]+'\t'+str(item[1]));
i += 1
#循环最后写
shopping_car = [0 for i in range(len(products))] #购物车
count = 0 #买了几件东西
sum = 0 #花了多少钱
while True:
id = input('请输入待购买的商品编码:')
if id.isdigit():
id = int(id)
if id < 0 or id >len(products)-1:
print('商品编码超出范围,请重新输入。')
continue
else:
shopping_car[id] += 1
count += 1
elif id.isalpha() and id == 'q':
if count == 0:
print('您未购买任何商品,欢迎下次光临!')
else:
print('------您已购买------')
i = 0
for num in shopping_car:
if num != 0:
print(products[i][0]+'\t'+str(products[i][1])+'\t'+str(num)+'个'+'\t'
+str(int(products[i][1])*num)+'元'+'\t')
sum += products[i][1]*num
i += 1
print('共计;'+str(sum)+'元')
exit() #系统退出
else:
print('输入格式有误,请输入数字。')
输出:
------ 商品列表 ------
0 iphone 6888
1 MacPro 14800
2 xiaomi6 2499
3 Coffee 31
4 Book 60
5 Nike 699
请输入待购买的商品编码:1
请输入待购买的商品编码:2
请输入待购买的商品编码:5
请输入待购买的商品编码:3
请输入待购买的商品编码:3
请输入待购买的商品编码:w
输入格式有误,请输入数字。
请输入待购买的商品编码:123
商品编码超出范围,请重新输入。
请输入待购买的商品编码:q
------您已购买------
MacPro 14800 1个 14800元
xiaomi6 2499 1个 2499元
Coffee 31 2个 62元
Nike 699 1个 699元
共计;18060元
Process finished with exit code 0
元组
基本知识
写在()中,元素不可修改,元素用逗号隔开,可重复,元素可以包含可变对象如列表。注意,定义只有一个元素的元组时,必须加逗号。
tup1 = ()
tup2 = (40) #不加逗号
tup3 = (40,) #加逗号
print(tup1)
print(type(tup2))
print(type(tup3))
输出:
()
<class 'int'>
<class 'tuple'>
元组常见操作
访问切片遍历
类似列表,访问用索引,切片区间左闭右开。
增删改查
增
元组之间的连接是可行的。注意,这种操作其实是创建了一个新的元组。
tup1 = (1,'a',[1,23,5])
tup2 = (3,4,'b')
print(tup1+tup2)
输出:
(1, 'a', [1, 23, 5], 3, 4, 'b')
删
del tuple 直接删除整个变量元组,清空了内存。
tup1 = (1,'a',[1,23,5])
del tup1 #直接删除了整个元组
print(tup1)
输出:
NameError: name 'tup1' is not defined
改
不支持每个元素的赋值。
tup1 = (1,'a',[1,23,5])
tup1[1]=2
print(tup1)
输出:
TypeError: 'tuple' object does not support item assignment
但元组的可变元素例如列表的元素是可变的。
tup1 = (1,'a',[1,23,5])
tup1[2][0]=2
print(tup1)
输出:
(1, 'a', [2, 23, 5])
查
见元组的访问。
其他的一些操作
1.tuple.count(ele) 类似列表,得到重复元素个数
2.min(tuple),max(tuple),len(tuple) 类似列表
3.tuple() 把其他类型对象转换为元组。
字典
基本知识
写在{}中,字典是无序的对象集合,使用键-值对储存,查找速度极快。键必须使用不可变类型,同一个字典中,键必须唯一。
字典常用操作
访问遍历
1.使用键来访问值,值内部也可以访问。
dict1 = {1:2,'我':'你','a':[1,2,3]}
print(dict1['我'])
print(dict1['a'][1])
输出:
你
2
直接访问不存在的键,会报错KeyError。但可以用dict.get(key),若不存在,默认返回None。
dict1 = {1:2,'我':'你','a':[1,2,3]}
print(dict1.get('aba'))
print(dict1.get('aba','No')) #修改未找到时的默认值
print(dict1.get(1))
输出:
None
No
2
注意,无法切片。
dict1 = {1:2,'我':'你','a':[1,2,3]}
print(dict1[0:2:1])
输出:
TypeError: unhashable type: 'slice'
2.遍历
直接for循环,keys见下的查。
dict1 = {1:2,'我':'你','a':[1,2,3]}
for key in dict1.keys():
print(key,end = ' ')
输出:
1 我 a
增删改查
增
新建一个键值对
dict1 = {1:2,'我':'你','a':[1,2,3]}
dict1['sb']='wsnb'
print(dict1)
输出:
{1: 2, '我': '你', 'a': [1, 2, 3], 'sb': 'wsnb'}
删
1.del dict.[key] 直接删除整个键值对。
dict1 = {1:2,'我':'你','a':[1,2,3]}
del dict1['a']
print(dict1)
输出:
{1: 2, '我': '你'}
还可以直接删除整个字典。
dict1 = {1:2,'我':'你','a':[1,2,3]}
del dict1
print(dict1)
输出:
NameError: name 'dict1' is not defined
2.clear 清空整个字典的键值对,但字典仍存在,只是变成了空字典。
dict1 = {1:2,'我':'你','a':[1,2,3]}
dict1.clear()
print(dict1)
输出:
{}
改
类似增,直接通过索引值修改。
查
1.键的查询(类似遍历)
dict.keys() 得到字典的所有键,注意:输出为列表形式,且()不能有东西。
dict1 = {1:2,'我':'你','a':[1,2,3]}
print(dict1.keys())
print(dict1.keys(0))
输出:
dict_keys([1, '我', 'a'])
TypeError: keys() takes no arguments (1 given)
2.值的查询
dict.values() 类似键。
3.项的查询
dict.items 得到所有的键值对。键值对存储在元组中,元组又作为元素存储在列表中。
dict1 = {1:2,'我':'你','a':[1,2,3]}
print(dict1.items())
print(dict1.items(1))
输出:
dict_items([(1, 2), ('我', '你'), ('a', [1, 2, 3])])
TypeError: items() takes no arguments (1 given)
项的遍历
1.通过for的两个参数。
dict1 = {1:2,'我':'你','a':[1,2,3]}
for key,value in dict1.items(): #可以直接查找每一个键值
print('{}:{}'.format(key,value),end = ' ')
输出:
1:2 我:你 a:[1, 2, 3]
2.enumerate() 枚举函数可以同时查出列表或元组的所以元素及其索引。
list1 = ['a','b','c','d'] #元组也可以
print(enumerate(list1))
for i,x in enumerate(list1):
print(i,x,end='---')
输出:
<enumerate object at 0x000001F4F4944D80>
0 a---1 b---2 c---3 d---
其他
1.len(dict) 获取字典长度,即键值对个数。
2.max(dict) min(dict) 获取最大,最小的Key.
3.dict() 把其他对象(嵌套列表)转换为字典。
dict1 = dict([(1,2),('a','b')]) #元素为元组,且要求元组长度一样
print(dict1)
输出:
{1: 2, 'a': 'b'}
dict1 = dict([([1,2],['a','b'])]) #元素为列表,报错
print(dict1)
输出:
TypeError: unhashable type: 'list'
2.dict1.update(dict2) 合并字典,dict1为合并后的字典。
dict1 = {'a':1,'b':2}
dict2 = {'c':3}
dict1.update(dict2)
print(dict1)
输出:
{'a': 1, 'b': 2, 'c': 3}
2.dict(zip(list1,list2)) 将两个列表转换为字典。dict1转换为键,dict转换为值。
list1 = [1,2,3,4]
list2 = ['a','b','c','d']
dict1 = dict(zip(list1,list2))
print(dict1)
输出:
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
若两个列表不等长,则转换为长度为更少列表长度的字典。
list1 = [1,2,3,4]
list2 = ['a','b','c']
dict1 = dict(zip(list1,list2))
print(dict1)
print(len(dict1))
输出:
{1: 'a', 2: 'b', 3: 'c'}
3
集合
基本知识
写在{}中,集合与字典类似,但集合只是键的集合,不储存值。元素不能重合(可以去重),无序。就是数学上的集合概念,可以进行交集&,并集|,差集-操作。
数据种类总结
有序性 可变性
列表[] 1 1
元组() 1 0
字典{} 0 key不可变,val可变
集合{} 0 1(不重复)
4.函数
4.1概念
独立的代码块。
4.2函数的定义与调用
4.2.1定义函数
普通函数
#定义
def printinfo():
print('------------------------')
print(' 人生苦短,我用python ')
print('------------------------')
#调用
printinfo()
输出:
带参数的函数
def average(a,b):
c = (a + b)/2
print(c)
print(average(1,5))
输出:
3.0
带返回值的函数
def average(a,b):
return (a+b)/2
print(average(1,5))
输出:
3.0
多个返回值
def divid(a,b):
shang = a//b
yushu = a%b #取余数
return shang,yushu
sh,yu = divid(8,3) #使用多个值来接收返回值
print(sh,yu)
输出:
2 2
注意,range()左闭右开。
练习题
#1
def printOneLine():
print('_'*120)
#2
import random
def printNLines(n):
for i in range(1,int(n+1)):#答案可以使用while
printOneLine()
printNLines(4)
#3
def sumM(a,b,c):
x = (a+b+c)
return x
#4
def average1(a,b,c):
x = sumM(a,b,c)/3
return x
4.2.2全局变量和局部变量
函数内部定义的变量就是局部变量。不同的函数定义局部变量时可以使用相同的名字。
若全局变量与局部变量名字一样,则只有在调用函数的时候会按照局部变量的值显示,其他情况均是全局变量。
a = 100 #全局变量
def test():
a = 300 #局部变量
print('函数里的a:',a)
test()
print('函数外的a:',a)
输出:
函数里的a: 300
函数外的a: 100
若要在函数内修改全局变量,需要用global var 声明。
a = 100 #全局变量
def test():
global a #声明调用全局变量
a = 300 #局部变量
print('函数里的a:',a)
test()
print('函数外的a:',a)
输出:
函数里的a: 300
函数外的a: 300
5.文件操作
5.1文件的打开与关闭
5.1.1打开文件
open(文件名,访问模式) 可以打开一个已经存在的文件,也可以创建一个新文件。
f = open('隐私保护','w')#写模式
默认在当前文件夹生成。
关闭文件:
f = open('隐私保护','w')
f.close()
无输出。
模式
‘w'模式
写入文件。
f = open('test.txt','w') #'w'写入模式
f.write('hello,world!')#写入字符串
f.close()
'r'模式
1.read() 读取指定的字符,开始时定位在文件头部,每执行一次向后移动相应的字符数。
f = open('test.txt','r') #'r'只读模式
content = f.read(5) #读出5个字符
print(content)
content = f.read(5) #在往后读取五个字符
print(content)
f.close()
输出:
hello
,worl
2.readlines() 一次性读取全部文件为列表,每行一个字符串。
f = open('test.txt','r')
content = f.readlines() #读出所以行,每一行作为一个元素保存在列表中
print(content)
content =
f.close()
输出:
['hello,world!\n', 'hello,world!\n', 'hello,world!hello,world!\n', '\n', '\n']
还可以分行输出:
f = open('test.txt','r')
content = f.readlines() #读出所以行,每一行作为一个元素保存在列表中
print(content)
#分行输出
i = 1
for temp in content:
print('{}:{}'.format(i,temp))
i+=1
f.close()
输出:
1:hello,world!
2:hello,world!
3:hello,world!hello,world!
4:
3.readline() 只能读一行,开始从第一行读起,每执行一次向后移动相应的行数。
f = open('test.txt','r')
content = f.readline()
print('{}:{}'.format(1,content))#读一行
content = f.readline()
print('{}:{}'.format(2,content))#读第二行
f.close()
输出:
1:hello,world!--1
2:hello,world!--2
文件的相关操作
重命名文件
需要引入os 模块,再使用rename(需要修改的文件名,新的文件名)
import os
os.rename('test.txt','test1.txt') #修改为了text1.txt
删除文件
os模块的remove(待删除的文件名)
import os
os.remove('test.txt')
若文件不存在,则报错。
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: 'test.txt'
创建删除文件夹
1.创建文件夹
import os
os.mkdir('test')#可以修改路径,请百度
2.删除文件夹
import os
os.rmdir('test')
获取当前目录
import os
print(os.getcwd())
输出:
G:\work\python works\project1\venv
6.异常处理
异常捕获
直接运行以下代码:
print('----test----1----')
f = open('123.txt','r') #只读模式打开一个不存在的文件
print('----test----2----')
输出:
----test----1----
Traceback (most recent call last):
File "G:/work/python works/project1/venv/demo1.py", line 3, in
f = open('123.txt','r') #文件并不存在
FileNotFoundError: [Errno 2] No such file or directory: '123.txt'
可见,第一句print运行了,然后报错。
使用try,错误相同时
可以被捕获:
try:#以下代码可能发生问题
print('----test----1----')
f = open('123.txt','r') #文件并不存在
print('----test----2----')
except IOError: #文件没找到属于IOError(输入输出异常)
pass #捕获异常后,代码执行到这里
输出:
----test----1----
并没有报错。
错误不同时
try:
print(num) #num不存在,是NameError
except IOError:
print('产生异常了')
输出:
Traceback (most recent call last):
File "G:/work/python works/project1/venv/demo1.py", line 2, in
print(num)
NameError: name 'num' is not defined
若要捕获多个异常
try:
print(num)
f = open('123')
except (IOError,NameError): #同时捕获IOError和NameError
print('产生异常了')
输出:
产生异常了
了解出现什么异常
try:
print(num)
f = open('123')
except (IOError,NameError) as result: #将异常信息以字符串的形式储存在result这一变量中
print('产生异常了')
print(result)
输出:
产生异常了
name 'num' is not defined
捕获所有异常
try:
print(num)
f = open('123')
except Exception as result: #Exception为所有异常
print('产生异常了')
print(result)
输出:
产生异常了
name 'num' is not defined
with open
with open自带异常处理。
嵌套
finally
finally表示不管结果,一定要执行的语句。一般用于文件打开时中有可能出现异常时,最后关闭文件以保护文件。
import time
try:
f = open('123')
try:
while True:
content = f.readLine()
if len(content) == 0:
break
time.sleep(2) #休眠两秒,以便操作。
print(content)
finally: #若上面的操作导致文件中断或异常,便可关闭来保护文件
f.close()
print('文件关闭')
except Exception as result:
print('发生异常')
作业
最简:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?