文章目录
python程序设计复习
1.python编程时注意点(未完待续)
- 注意该方法是原址的还是返回一个值
- 0.0和0真不一样,有时候自动类型转换会失败
2.基本数据类型
1.四种进制表示
- 1010 十进制
- 0b010 二进制
- 0o123 八进制
- 0x9a 十六进制
2.浮点数的四舍五入
round(x,d)
对x四舍五入,d是小数截取位数
3.科学计数法
9.6E8
表示 9.6 × 1 0 8 9.6\times 10^8 9.6×108
4.复数类型
z.real
z.imag
5.字符串类型
- 几个生疏的函数
hex(x)#整数x的16进制字符串
oct(x)#整数x的8进制字符串
chr(u)#返回unicode对应的char
ord(x)#返回char对应的unicode
- 字符串处理方法
string.lower()
string.upper()
string.split(sep)
string.count(sub)#返回sub在字符串中出现的次数
string.replace(old,new)#返回一个副本
string.center(width,[,fillchar])#根据width居中,fillchar为填充元素
string.strip(chars)#从str中去掉在其左侧和右侧chars中列出的字符
string.join(iter)#在iter变量除最后元素外每个元素后增加一个str
- 字符串类型的格式化
"{}".format()
{index:<用于填充的单个字符> <对齐方式<^>> <宽度> <,千分位> <.精度> <类型>}
6.time库的使用
- 时间获取
import time
time.time()#获取当前的时间戳,计算机内部时间,浮点数
time.ctime()#获取当前时间,以易读的方式,字符串
time.gmtime()#获取当前时间,计算机可以处理的格式(time_struct格式)
- 时间格式化
strftime(tpl,ts)
tpl是格式化模板字符串,ts是struct_time型数据
t=time.gmtime()
f=time.strftime("%Y-%m-%d %H:%M:%S",t)
f='2021-11-26 12:55:20'
time.strptime(f,"%Y-%m-%d %H:%M:%S")
两者互为逆操作
- 其他一些函数
import time
time.perf_counter()#用于计时,连续调用后作差
time.sleep(second)#程序终止second秒
3.程序的控制结构
1.异常处理
try:
pass
except:
pass
else:
pass
finally:
pass
else对应的语句块可以视作对于try中未发生异常的奖励;finally对应的语句块一定执行。
2.循环
while <条件>:
pass
else:
pass
循环与else。else可以作为正常完成循环的奖励
3.random库的使用
基础函数
import random
random.seed(10)#设置随机数种子
random.random()#随机生成(0.0,1.0]的随机小数
整数拓展函数
random.randint(a,b)#[a,b]之间的整数
random.randrange(m,n[,k])#[m,n)以k为步长的随机整数
random.getrandbits(k)#获得k比特字长的随机整数
小数拓展函数
random.uniform(a,b)#生成[a,b]之间的随机小数
随机选取函数
random.choice([1,2,3,4,5,6,7])#从序列中随机选取一个元素
random.shuffle([1,2,3,4,5,6,7])#返回随机打乱后的序列
4.函数和代码复用
1.lambda匿名函数
格式
<func_name>=lambda <参数>:<表达式>
举例
f=lambda x,y:x+y
f(10,15)#result is 25
f=lambda : "lambda func"
print(f())# result is 'lambda func'
5.组合数据类型
1.集合set
- 集合元素间无序,每个元素不可以重复。
- 集合元素不可更改,不能是可变数据类型
- 集合用{}表示,建立空集合需要用set()
- 集合操作符
S|T #并,返回新集合
S|=T #并,更新集合S
S-T #差,返回新集合
S&T #交,返回新集合
S^T #补,返回新集合
S<=T #返回true,false,判断子集关系
S>=T #同上
- 集合的方法
S.add(x)#将x加入S
S.discard(x)#移除S中的x,如果x不在S中,不报错
S.remove(x)#移除S中的x,如果x不在S中,报错
S.clear()
S.pop()
S.copy()
len(S)
x in S
x not in S
set(x)
2.序列类型
- 序列类型通用操作
s+t#连接两个序列s和t
s*n#将序列s复制n次
s.index(x)#返回第一次出现x的位置
s.index(x,i,j)#返回序列从i开始到j位置第一次出现x的位置
s.find(x)#同index,如果找不到返回-1
s.count(x)#返回s中出现x的总次数
要注意,find如果没找到,返回-1;而index没找到,报错。
- 列表类型操作
ls[i]=x#替换
ls[i:j:k]=lt#用列表lt替换ls切片后所对应的元素子列表
del ls[i]#删除列表ls的第i个元素
del ls[i:j:k]#删除
ls.append(x)
ls.clear()
ls.copy()
ls.insert(i,x)#第i个位置插入x
ls.pop(i)#将列表第i位置元素取出并删除
ls.remove(x)#将列表第一次出现的x删除,没有的话会报错
ls.reverse()
- 字典类型操作
del d[k]#删除字典d中键k对应的数据值
k in d #判断键k是否在字典中
d.keys()#返回key(不是列表)
d.values()#返回value(不是列表)
d.items()
d.get(k,<default>)#key k存在,返回value,不存在返回default
d[k]
d.pop(k,<default>)#key k存在,取出value,不存在返回default
d.popitem()#随机取出一个键值对
d.clear()
len(d)
3.jieba库的使用
import jieba
jieba.lcut(s)
精确模式,返回一个列表类型的分词结果。
这里给出一个例子,其中的一些字典的操作非常精妙
import jieba
with open(filename,'r',encoding='utf-8') as fp:
content=fp.read()
words=jieba.lcut(content)
d={}
for word in words:
if len(word)<=2:
continue
else:
d[word]=d.get(word,0)+1
items=list(d.items())
items.sort(key=lambda x:x[1],reverse=True)
print(items[0][0])#输出词频最大且length>=2的单词
6.文件和数据格式化
读取
- 读取整个文件,全文本操作
with open(filename) as fp:
txt=fp.read()
print(txt.rstrip())
注意:read读到文件末尾会自动加入一个换行符,可以使用rstrip删去
fp.read(size=-1)
读入前size的长度
- 逐行读取
with open(filename) as fp:
for line in fp:
print(line.rstrip())
with open(filename) as fp:
lines=fp.readlines()
#lines is a list
注意:文件中每行的末尾都有一个看不见的换行符
fp.readlines(hint=-1)
读入–前hint行–
fp.readline(size=-1)
读入一行前size个字符
- 其他
open(filename,‘rb’)二进制文件形式打开文件
open(filename,‘rt’)文本文件形式打开文件
写入
- 字符串的多行写入
with open(filename,'w') as fp:
fp.write('Hello!\n')
fp.write('world\n')
ls=['1\n','2\n','3\n']
with open(filename,'w') as fp:
fp.writelines(ls)
注意:只能写入字符串,其他类型的话要做强制类型转换
- 文件操作指针
fp=open(filename,'w')
fp.seek(offset)
改变当前文件操作指针的位置。offset含义:0-文件开头,1-当前位置,2-文件结尾。比如fp.seek(0)
回到文件开头
csv数据文件的读写
- 一些用特殊分隔符分割的数据格式写入
考虑使用fp.write(','.join(list))
,用特殊分隔符的字符串,这里是csv
- 从csv格式文件读入数据
with open(filename) as fp:
ls=[]
for line in fp:
line=line.replace('\n','')
ls.append(line.split(','))
- 写入csv格式的文件
ls=[[],[],[]]#二维列表
with open(filename,'w') as fp:
for item in ls:
fp.write(','.join(item)+'\n')
7.一些函数和方法
isinstance(x,int)
string.islower()
8.典型代码
- 判断素数
def isPrime(n):
if n==1 or n==2:
return True
else:
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
- 判断完数
def isPerfect(m): #判断完数的函数
if isPrime(m) and isPrime(2**m-1):
s = 2**(m-1)*(2**m-1)
ls.append(s)
for i in range(2, s // 2 + 1):
if s % i == 0:
factor.append(i)
return s
else:
return False
- 黑色星期五
import datetime
year = int(input()) #输入任意年份
days = [datetime.date(year, i, 13) for i in range(1, 13)] #产生该年每个月13日 的列表
for i in days:
if i.isoweekday()==5:
print(i)
- 装箱问题
# 输入切分后逆序,得到6*6,5*5,4*4,3*3,2*2,1*1的箱子数量
ls = list(map(int, input().split()))
box_66 = ls[5] # 6*6,5*5,4*4的每个包裹各占一个集装箱
box_55 = ls[4]
box_44 = ls[3]
box_33 = (ls[2] + 3) // 4 # 3*3 的每4个包裹占一个集装箱
# 每个放6*6的箱子是满的
# 每个放5*5的箱子里空11个单元,能装11个1*1
# 每个放4*4的箱子里空20个单元,能装5个2*2,满
# 每个放1个3*3的箱子里空27个单元,能装5个2*2,余7个1*1
# 每个放2个3*3的箱子里空18个单元,能装3个2*2,余6个1*1
# 每个放3个3*3的箱子里空9个单元,能装1个2*2,余5个1*1
# 放3*3的集装箱的空闲单元数量(4 - ls[3] % 4) * 9 if ls[3] % 4 != 0 else 0
# 放6*6,5*5,4*4,3*3的集装箱中能容纳2*2的箱子的数量box_22_capacity
# box_22_capacity = 5 * ls[3] + ((4 - ls[2] % 4) * 9 if ls[2] % 4 != 0 else 0)
box_22_capacity = 5 * ls[3] + (ls[2] % 4 == 1) * 5 + (ls[2] % 4 == 2) * 3 + (ls[2] % 4 == 3) * 1
# print(box_22_capacity)
if ls[1] < box_22_capacity: # 如果前3种箱子空余位置多于2*2的数量,不需要单独占用新箱子
box_22 = 0 # 空闲1*1的单元为总空闲单元-ls[1]*4
# 5*5 4*4 3*3总空闲单元减2*2的箱子占用的单元数为剩余1*1的单元数
box_11_capacity = 11 * ls[4] + 20 * ls[3] + (ls[2] % 4 == 1) * 27 + (ls[2] % 4 == 2) * 18 + (ls[2] % 4 == 3) * 9 - ls[1] * 4
# print(box_11_capacity)
else:
box_22 = (ls[1] - box_22_capacity + 8) // 9
box_22_left = (ls[1] - box_22_capacity) % 9 # 未满的2*2的箱子里的2*2的箱子数量
# print(box_22)
# print(box_22_left)
# 5*5 4*4 3*3总空闲单元减2*2的箱子占用的单元数为剩余1*1的单元数
box_11_capacity = 11 * ls[4] + 20 * ls[3] + (ls[2] % 4 == 1) * 27 + (ls[2] % 4 == 2) * 18 + (ls[2] % 4 == 3) * 9 - box_22_capacity * 4 + (36 - box_22_left * 4)
# print(box_11_capacity)
# 放了box_22_left个2*2的箱子里能装36-box_22_left*4个1*1的箱子
if ls[0] < box_11_capacity:
box_11 = 0
else:
box_11 = (ls[0] - box_11_capacity + 35) // 36
total = box_66 + box_55 + box_44 + box_33 + box_22 + box_11
# print(box_11, box_22, box_33, box_44, box_55, box_66)
print(total)
3] + (ls[2] % 4 == 1) * 27 + (ls[2] % 4 == 2) * 18 + (ls[2] % 4 == 3) * 9 - box_22_capacity * 4 + (36 - box_22_left * 4)
if ls[0] < box_11_capacity:
box_11 = 0
else:
box_11 = (ls[0] - box_11_capacity + 35) // 36
total = box_66 + box_55 + box_44 + box_33 + box_22 + box_11
print(total)