Python笔记

代码越简单越好,方便维护,宁愿空间换时间

Index:

1.一行代码实现“前100中,对‘3的倍数’的数求和”(列表推导式)
2.将字符串文本“¥12345.6789元”,加上千元内随机金额后,变为保留2位小数的字符串文本
3.打印九九乘法表
4.打印九九乘法表(完美对齐版本)
5.判断某一天是当年的第几天
6.一个整数加上100是完全平方数,加上268还是完全平方数,求这个整数(对比电脑性能)
7.随机输入5个数,按大小重新排列
8.分解质因数(对比电脑性能)
9.找出字符串中数字、字母、空格、其他类字符的个数
10.S=a+aa+aaa+aaaa+…+aaaaaaa(a是整数,输入;相加次数,也是输入)
11.打印菱形
12.输入n个字符,倒序输出
13.输入10个正整数,输出第二大数的序号
14.输入1个不多余5位的正整数,判断位数,然后逆序打印
15.类和对象的深入理解
16.请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母
17.有序列表插入元素:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中
18.矩阵相加
19.函数交换变量
20.多个人按顺序轮流报数,报到3的人退出圈子,然后下个人再从1开始报数,顺序不变,一直循环报数,最后剩下几号?
21、实例化webdriver的2种方式(path型,指定路径型)
22、多进程、多线程的案例
23、pycharm文件开头设置
24、pycharm注释颜色
25、普通文件操作的一些记录
26、迭代器、生成器的一些练习
27、引用、调用、内包、外包、闭包、装饰器基础-闭包
28、闭包之上-装饰器
29、上下文管理器
30、类和对象的复习
31、多进程多线程练习记录
32、多线程模拟生产者消费者问题
33、re正则表达式练习记录
34、时间标准库time,datetime,数学标准库math,random,练习记录
35、os.path,pathlib.Path练习记录
36、pip安装
37、根据起点、终点、间隔值,生成一个由重多子列表作为元素的大列表对象
38、多维数组的排序
39、列表方法操练
40、字符串方法操练
41、字典方法操练
42、简单的os操作
43、python中的队列初探

1.一行代码实现“前100中,对‘3的倍数’的数求和”(列表推导式)

print(sum(i for i in range(0,101,3)))#对“3的倍数”的数求和
print(sum(i for i in range(0,101,2)))#对“2的倍数”的数求和

1683
2550

PS:不要求最简的话,使用while循环、for循环都可以得出结论(列表推导式其实还可以带if哦)

2.将字符串文本“¥12345.6789元”,加上千元内随机金额后,变为保留2位小数的字符串文本

import random#导入随机模块
s='¥12345.6789元'
s1,s2,s3=s[0],s[1:-1],s[-1]#一次多赋值几个
s2=f'{float(s2)+random.uniform(0,1000):.2f}'#转类型相加再转回来
s22='{float(s2)+random.uniform(0,1000):.2f}'#没加f
print(s1+s2+s3)#字符串文本拼接
print(s1,s2,s3,s22,sep='-')#看看各元素

¥12754.67元
¥-12754.67-元-{float(s2)+random.uniform(0,1000):.2f}

PS:字符串切片,转类型,拼接

3.打印九九乘法表

for i in range(1,10):
    for j in range(1,i+1):
        print(f'{j}×{i}={j*i}',end=' ')
        # print("%d*%d=%2d"%(j,i,j*i),end=' ')#老版本等价写法
    print('')

1×1=1
1×2=2 2×2=4
1×3=3 2×3=6 3×3=9
1×4=4 2×4=8 3×4=12 4×4=16
1×5=5 2×5=10 3×5=15 4×5=20 5×5=25
1×6=6 2×6=12 3×6=18 4×6=24 5×6=30 6×6=36
1×7=7 2×7=14 3×7=21 4×7=28 5×7=35 6×7=42 7×7=49
1×8=8 2×8=16 3×8=24 4×8=32 5×8=40 6×8=48 7×8=56 8×8=64
1×9=9 2×9=18 3×9=27 4×9=36 5×9=45 6×9=54 7×9=63 8×9=72 9×9=81

PS:要处理好对齐细节的话,得老版本写法

4.打印九九乘法表(完美对齐版本)

for i in range(1,10):
    for j in range(1,i+1):
        # print(f'{j}×{i}={j*i}',end=' ')#新版本写法
        print("%d*%d=%2d"%(j,i,j*i),end=' ')#老版本等价写法
    print('')

11= 1
1
2= 2 22= 4
1
3= 3 23= 6 33= 9
14= 4 24= 8 34=12 44=16
15= 5 25=10 35=15 45=20 55=25
1
6= 6 26=12 36=18 46=24 56=30 66=36
1
7= 7 27=14 37=21 47=28 57=35 67=42 77=49
18= 8 28=16 38=24 48=32 58=40 68=48 78=56 88=64
19= 9 29=18 39=27 49=36 59=45 69=54 79=63 89=72 9*9=81
在这里插入图片描述
%d #数字普通输出;
%2d #数字按宽度为2,右对齐方式输出,左边补空格;
%02d#数字按宽度为2,右对齐方式输出,左边补0;
%.2d#输出整形时最少输出2位,不够以0占位,小数的话只要整数部分(100→100,2→02,3.777→03);
在这里插入图片描述

5.判断某一天是当年的第几天

a=input('请输入年月日代表的8位纯数字,例如“20201204”代表2020/12/04:')
year,month,day,sum=int(a[0:4]),int(a[4:6]),int(a[6:8]),0
b=(31,28,31,30,31,30,31,31,30,31,30,31)
for i in range(1,12):
    if month >= i+1:
        sum+=b[i-1]
    else:
        break #为提高效率,采用break
if (year%4==0 and year%100!=0 or year%400==0) and month>=3 :
    sum+=1
sum+=day
print(f'{year}/{month}/{day}这一天是当年的第{sum}天')

在这里插入图片描述

6.一个整数加上100是完全平方数,加上268还是完全平方数,求这个整数(对比电脑性能)

import math,time
print(time.ctime())#考察电脑性能
for i in range(1,9999999,1):
    if round(math.sqrt(i+100))==math.sqrt(i+100) \
            and round(math.sqrt(i+268))==math.sqrt(i+268):
        print(i)
print(time.ctime())#考察电脑性能
import math,time
start=time.time()
for i in range(1,10000000,1):
    if round(math.sqrt(i+100))==math.sqrt(i+100) \
            and round(math.sqrt(i+268))==math.sqrt(i+268):
        print(i)
end=time.time()
#考察电脑性能
print(end-start)

ROG魔霸新锐i7十代-只需4秒,ThinkPad T470s i5七代要12秒

7.随机输入5个数,按大小重新排列

s=[]
for i in range(5):
    s.append(input(f'请输入第{i+1}个数:'))
s.sort()    #从小到大
print(s,type(s)) 
s.reverse() #从大到小
print(s,type(s)) 

运行效果

var s=[1.234,0,-67,99,55];
s.sort();//从小到大排序
console.log(s)
console.log('sort()排序后结果为【'+s+'】')
s.reverse() //当前顺序的倒序排序
console.log('reverse()倒序排序后结果为【'+s+'】')

运行效果

8.分解质因数(对比电脑性能)

import math
def single(x):
    if x in (1,2,3) :
        return True
    else:
        for i in range(2,math.ceil(math.sqrt(x))):
            if x%i==0:
                return False
        return True
a=int(input('请输入1000万以内、大于1的正整数:'))
a1,b,c=a,[],''
if single(a)==True:
    print(f'a={a}')
else:
    for i in range(2,math.ceil(a/2)):
        if single(i)==True:
            while a%i==0:
                a=a/i
                b.append(i)
print(b)
for i in range(0,len(b)):
    c=c+f'{b[i]}*'
d=f'{a1}='+c
print(d[0:-1])

在这里插入图片描述

function single(x)
{   if(x in [1,2,3]) {return true;}
    else 
        {
            for(var i=2;i<=x;i++)
            {
               if ( x%i === 0){return false;}
               return true;
            }
        }
}
var a=146965;
var a1=a;
var b=[];
var c='';
if (single(a)==true){console.log('a='+a+'')}
else 
 {
    for(var i=2;i<=Math.ceil(a/2);i++)
    {
        if (single(i)==true)
        {
            while(a%i===0){a=a/i;b.push(i)}
        }
    }
 }
console.log(b)
for (var i=0;i<b.length;i++)
{
    c=c+''+b[i]+'*'
}
var d=''+a1+'='+c
console.log(d[0,-1])

js的实现不知道错在哪里,以后熟练了,再来纠错
在这里插入图片描述

9.找出字符串中数字、字母、空格、其他类字符的个数

方法一:

import re,sys
a=input('请输入字符串:')
a1=len(re.findall('\s',a))
a2=len(re.findall('\d',a))
a3=len(re.findall('[a-zA-Z]',a))
a4=len(a)-a1-a2-a3
print(f'空格:{a1}\n数字:{a2}\n字母:{a3}\n其他类:{a4}')
sys.stdout.write(f'空格:{a1}\n数字:{a2}\n字母:{a3}\n其他类:{a4}')
sys.stdout.write('\n空格:'+str(a1))
sys.stdout.write('数字:'+str(a2))
sys.stdout.write('字母:'+str(a3))
sys.stdout.write(f'其他:{a4}')

在这里插入图片描述
方法二:

import sys
a = input("input:")
letter,space,number,others=0,0,0,0
for b in a:
    if b.isalpha():
        letter += 1
    elif b.isspace():
        space += 1
    elif b.isdigit():
        number +=1
    else :
        others+=1
print(f"字母有{letter}个,空格有{space}个,数字{number}个,其他类{others}个")
sys.stdout.write(f"字母有{letter}个,空格有{space}个,数字{number}个,其他类{others}个")

在这里插入图片描述

拓展:
在这里插入图片描述

10.S=a+aa+aaa+aaaa+…+aaaaaaa(a是整数,输入;相加次数,也是输入)

import sys
a=int(input('请输入数字:'))
a1=a
b=int(input('请输入计算次数:'))
c=[]
s=0
sys.stdout.write(f'结果=0')
for i in range(b):
    c.append(a)
    s+=a
    a=a*10+a1
    sys.stdout.write('+'+f'{c[i]}')
sys.stdout.write(f'={s}')

在这里插入图片描述

11.打印菱形

方法一:

import sys
n=int(input('请输入最长行的行标:'))
for i in range(0,n):
    print(' '*(n-i-1),sep='',end='')
    print('*'*(2*i+1),sep='',end='\n')
for i in range(1,n):
    print(' '*(i),sep='',end='')
    print('*'*(2*n-1-2*i),sep='',end='\n')

在这里插入图片描述
方法二:

a=int(input(':'))
b='*'
e=[]
for i in range(1,a+1):
    if a%2!=0:
        if i<=(a+1)/2:
            e.append((2 * i - 1) * '*')
            print(' '*(round((a+1)/2)-i),e[i-1])
        if i>(a+1)/2:
            print(' '*(-(round((a+1)/2)-i)),e[-(i-(round((a+1)/2)-1))])
    if a%2==0:
        if i<=a/2:
            e.append((2 * i - 1) * '*')
            print(' '*(round(a/2)-i), e[i-1])
        if i>a/2:
            print(' '*(-((round(a/2)+1)-i)),e[round(a/2)-i])

在这里插入图片描述

12.输入n个字符,倒序输出

方法一二:

# 输入n个字符,倒序输出
def out1(n):
    n=int(n)
    x = input('请输入字符:')
    if n<=1:
        print(x,end=',')
    else:
        out1(n-1)
        print(x,end=',')
out1(6)
print('\n')
def out2(n):
    x=[]
    for i in range(n):
        x.append(input('请输入字符:'))
    x.reverse()
    for i in x:
        print(i,end=',')
out2(6)

在这里插入图片描述
方法三:

def resite(str):
    if len(str)!=1:
        resite(str[1:])
    else:
        pass #逻辑完整性
    print(str[0],end='')
resite(input('请输入字符串 :'))

在这里插入图片描述

13.输入10个正整数,输出第二大数的序号

# 输入10个正整数,输出第二大数的序号
def second():
    x=[]
    for i in range(10):
        x.append(float(input(f'请输入第{i+1}个数字:')))
    x.sort()
    print(x)
    print(x[-2])
second()

在这里插入图片描述

14.输入1个不多余5位的正整数,判断位数,然后逆序打印

傻不傻,直接len()取长度,字符串逆序[::-1]打印就行了。

# 输入1个不多余5位的正整数,判断位数,然后逆序打印
import sys
x=int(input('请输入不多余5位的正整数:'))
a=x//10000
b=x%10000//1000
c=x%1000//100
d=x%100//10
e=x%10
if a!=0:
    print(f'这是5位数:{e},{d},{c},{b},{a}')
elif b!=0:
    print('这是4位数:',e,d,c,b)
elif c!=0:
    sys.stdout.write(f'这是3位数:{e},{d},{c}')
elif d!=0:
    sys.stdout.write(f'这是2位数:{e},{d}')
else:
    sys.stdout.write(f'这是1位数:{e}')

在这里插入图片描述

15.类和对象的深入理解

class test1:
    attr = 1
a1 = test1()
test1.attr = 0
print(a1.attr)
a1.attr = 4
a1.test = 6
a2 = test1()
print(a2.attr)
print(a1.attr, a1.test)
print(test1.__dict__, a1.__dict__)

class test2:
    attr = 2
b1 = test2()
b2 = test2()
b1.attr = 0
print(b2.attr)
print(test2.__dict__, b2.__dict__)

class test3:
    attr = 3
    def __init__(self):
        self.attr = 0
c = test3()
print(c.attr)
print(test3.__dict__, c.__dict__)

在这里插入图片描述
在这里插入图片描述

16.请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母

方法1:

# 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
# monday,tuesday,wensday,thursday,friday,saturday,sunday
def judge():
    a = input('请输入第1个字母:').lower()
    b = {'m': 'monday星期一', 'w': 'wensday星期三', 'f': 'friday星期五'}
    if a in ('m', 'w', 'f'):
        print('我猜你表达的是:', b[a])
    elif a in ('t'):
        a1 = input('请输入第2个字母:').lower()
        if a1 == 'u':
            print('我猜你表达的是:tuesday星期二')
        elif a1 == 'h':
            print('我猜你表达的是:thursday星期四')
        else:
            print('输入错误,重来')
            judge()
    elif a in ('s'):
        a2 = input('请输入第2个字母:').lower()
        if a2 == 'a':
            print('我猜你表达的是:saturday星期六')
        elif a2 == 'u':
            print('我猜你表达的是:sunday星期天')
        else:
            print('输入错误,重来')
            judge()
    else:
        print('输入错误,重来')
        judge()  
judge()

在这里插入图片描述
方法2:

a = input('输入第1个字母:')
while True:
    if a not in ('m', 't', 'w', 'f', 's'):
        a = input('输入第1个字母:')
    else:
        break
if a == 't' or a == 's':
    b = input('输入第二个字母:')
    while True:
        if b not in ('u', 'h', 'a', 'n'):
            b = input('输入第二个字母:')
        else:
            break
    if a == 't' and b == 'u':
        print('星期二')
    if a == 't' and b == 'h':
        print('星期四')
    if a == 's' and b == 'a':
        print('星期六')
    if a == 's' and b == 'u':
        print('星期天')
if a == 'm':
    print('星期一')
if a == 'w':
    print('星期三')
if a == 'f':
    print('星期五')

在这里插入图片描述
方法3:(该方法转载自-https://blog.csdn.net/weixin_41084236/article/details/81564963)

weekT={'h':'thursday',
       'u':'tuesday'}
weekS={'a':'saturday',
       'u':'sunday'}
week={'t':weekT,
      's':weekS,
      'm':'monday',
      'w':'wensday',
      'f':'friday'}
a=week[str(input('请输入第一位字母:')).lower()]
if a==weekT or a==weekS:
    print(a[str(input('请输入第二位字母:')).lower()])
else:
    print(a)

在这里插入图片描述
方法4:

week = {'t': {'u': 'tuesday', 'h': 'thursday'},
        's': {'a': 'saturday', 'u': 'sunday'},
        'm': 'monday',
        'w': 'wensday',
        'f': 'friday'}
a = week[(input('请输入第一位字母:')).lower()]
if a == 'monday' or a == 'wensday' or a == 'friday':
    print(a)
else:
    print(a[(input('请输入第二位字母:'))])

在这里插入图片描述

17.有序列表插入元素:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

# coding:utf8
def sort(list,i):
    list.append(i)
    return sorted(list)
print(sort([1,4,8,5],-99))

在这里插入图片描述

18.矩阵相加

转载于https://blog.csdn.net/weixin_41084236/article/details/81564963

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]
res=[[0,0,0],
    [0,0,0],
    [0,0,0]]
for i in range(len(res)):
    for j in range(len(res[0])):
        res[i][j]=X[i][j]+Y[i][j]
print(res)

在这里插入图片描述

19.函数交换变量

def exchange(x,y):
    return (y,x)
x=1
y=2
x,y=exchange(x,y)
print(x,y)

在这里插入图片描述

20.多个人按顺序轮流报数,报到3的人退出圈子,然后下个人再从1开始报数,顺序不变,一直循环报数,最后剩下几号?

法一(余数修正法):

# coding:utf8
a=int(input('请输入人数(整数):'))
x,y,j=[],[],0
for i in range(1,a+1):
    x.append(i)
print(f'x={x}')
# x.pop(0)    #索引删除
# del x[0]    #索引删除
# x.remove(6) #值删除
# print(f'x={x}')
while len(x)>=2:
    for i in range(0,len(x)):
        if (i+1+j)%3==0:
            y.append(x[i])
        else:
            pass
    j = (len(x) + j) % 3
    print(y)
    for k in y:
        x.remove(k)
    y=[]
print(f'最开始的第{x[0]}号选手最终留了下来')

999人
在这里插入图片描述
法二(累积计数法):

n = int(input('请输入人数:'))
li_c = list(range(1, n + 1))
a = 0
while len(li_c) > 1:
    li_co = li_c[:]
    for i in range(len(li_co)):
        print(li_c)
        a = a + 1
        if a % 3 == 0:
            li_c.remove(li_co[i])
print(f'最后留下的是原来的第 {li_c[0]} 号。')

888人
在这里插入图片描述
21、实例化webdriver的2种方式(path型,指定路径型)

from selenium import webdriver
import time
#无path调用谷歌浏览器驱动
dr1=webdriver.Chrome(executable_path='D:\\ChromeDriver\\chromedriver.exe')
dr1.maximize_window()
dr1.implicitly_wait(15)
dr1.get('http://www.baidu.com')
time.sleep(1)
#有path调用谷歌浏览器驱动
dr2=webdriver.Chrome()
dr2.maximize_window()
dr2.implicitly_wait(15)
dr2.get('https://blog.csdn.net/Tiandao60')
time.sleep(1)
#无path调用火狐浏览器驱动
dr3=webdriver.Firefox(executable_path='D:\\GeckoDriver\\geckodriver.exe')
dr3.maximize_window()
dr3.implicitly_wait(15)
dr3.get('http://www.baidu.com')
time.sleep(1)
#有path调用火狐浏览器驱动
dr4=webdriver.Firefox()
dr4.maximize_window()
dr4.implicitly_wait(15)
dr4.get('https://blog.csdn.net/Tiandao60')
time.sleep(1)
# 无path调用IE浏览器驱动
dr5=webdriver.Ie(executable_path='D:\\IEDriverServer\\IEDriverServer.exe')
dr5.maximize_window()
dr5.implicitly_wait(15)
dr5.get('http://www.baidu.com')
time.sleep(1)
#有path调用IE浏览器驱动
dr6=webdriver.Ie()
dr6.maximize_window()
dr6.implicitly_wait(15)
dr6.get('https://blog.csdn.net/Tiandao60')
time.sleep(1)

22、多进程、多线程的案例

# coding=utf-8
"""
Author:刘源
Createtime:2021/07/26 00:12:27
Updatetime:2021/07/26 00:12:27
Description:
"""
import time,threading,os,pathlib,multiprocessing
file1=open('5W2H抓重点潜意识.txt','a')
file1.write('\n运行记录')
file1.write(time.ctime())
file1.write('---'+str(time.time()))
file1.close()

c=0
def loop(timer):
    global c
    c += 1
    c1=c
    print(f'{multiprocessing.current_process()}:循环内,当前子进程号是{os.getpid()},__name__是{__name__},',f'第{c1}次循环开始:{time.ctime()},持续时间是{timer}s,当前线程是{threading.current_thread()},当前线程数是{threading.active_count()}。')
    time.sleep(timer)
    print(f'{multiprocessing.current_process()}:循环内,当前子进程号是{os.getpid()},__name__是{__name__},',f'第{c1}次循环结束:{time.ctime()},持续时间是{timer}s,当前线程是{threading.current_thread()},当前线程数是{threading.active_count()}。')
print(f'{multiprocessing.current_process()}:主进程内,当前主进程号是{os.getppid()},当前子进程号是{os.getpid()},__name__是{__name__}')
# 多进程
if __name__=='__main__':
    p=[]
    p.append(multiprocessing.Process(target=loop,name='子进程1',args=(9,)))
    p.append(multiprocessing.Process(target=loop,name='子进程2',kwargs={"timer":7,}))
    p.append(multiprocessing.Process(target=loop,name='子进程3',args=(5,)))
    for i in p:
        i.start()
        time.sleep(1)
    loop(3)
# 多线程
t=[]
t.append(threading.Thread(target=loop,name='子线程1',args=(9,)))
t.append(threading.Thread(target=loop,name='子线程2',kwargs={"timer":7,}))
t.append(threading.Thread(target=loop,name='子线程3',args=(5,)))
for i in t:
    i.start()
    time.sleep(1)
loop(3)

23、pycharm文件开头设置
在这里插入图片描述
在这里插入图片描述
24、pycharm注释颜色
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
效果:
在这里插入图片描述
25、普通文件操作的一些记录

import time,threading,os,pathlib,multiprocessing,sys,codecs,re
file1=open('5W2H抓重点潜意识6.txt','a')
file1.write(f'\n{__file__}运行记录')
file1.write(time.ctime())
file1.write('---'+str(time.time()))
file1.close()
# 读取人名,集合去重
file2=open('threeState/name.txt','r',encoding='utf-8')
names=list(set(file2.read().split('|')))
print(names)
file2.close()
# 读取武器,集合去重
file3=open('threeState/weapon.txt','r',encoding='utf8')
weapons=file3.readlines()
print(weapons)
file3.close()
# 读取‘三国演义’全文
file4=open('threeState/sanguo1.txt','r',encoding='utf8')
txt=file4.read().strip().replace('\n','')
# print打印,用的是gbk编码
print(txt.encode('gbk','ignore').decode('gbk'))
file4.close()
# 统计人名出现次数
for name in names:
    print(name,len(re.findall(name,txt)))

26、迭代器、生成器的一些练习

# 简单迭代器
it1=iter(list(i for i in range(0,1001,5) if i%4==0))
while True:
    try:
        print(next(it1))
    except Exception as e:
        print('结束')
        break
# 生成器-特殊迭代器,定义
def frange(start,stop,step):
    x=start
    while x<stop:
        print('yield还会执行哦 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈')
        yield x
        x+=step
# next()访问迭代器-生成器
a=frange(1,99,2)
print(next(a))
print(next(a))
print(next(a))
print('$'*99)
# 遍历访问迭代器-生成器
for i in frange(100,200,15):
    print(i)

27、引用、调用、内包、外包、闭包、装饰器基础-闭包

# coding=utf-8
# encoding: utf-8
"""
Author:刘源
Createtime:2021/07/31 19:12:15
Updatetime:2021/07/31 19:12:15
Description:闭包与函数的引用、调用、嵌套、外包、内包,闭包=外包内包的引用调用
"""
import time,threading,os,pathlib,multiprocessing,sys,codecs,re,functools,sys
file1=open('LinuxPython5W2H-10.txt','a')
file1.write(f'{__file__}运行记录')
file1.write(time.ctime())
file1.write('---'+str(time.time())+'\n')
file1.close()
# 闭包-内外包-引用调用
def sum(a):
    def total(b):
        return a+b
    return total
print(type(sum(1)))
print(sum(1)(2))
# 计时装饰器
def countTime(func):
    start=time.time()
    def wrapper(*args,**kwargs):
        result= func(*args,**kwargs)
        end=time.time()
        print(f'耗时{end-start}s')
        return result
    return wrapper
# 语法糖调用计时装饰器
@countTime
def for1():
    a=[]
    for i in range(1,9999999):
        a.append(i)
    print('finish')
    return a
print(for1()[88])
# 用闭包实现类似迭代器、生成器的迭代、累加功能
def counter(first=0):
    count=first
    def addOne():
        nonlocal count
        count+=1
        return count
    return addOne
# 类似dr=webdriver.Chrome(),闭包内外包引用调用,类方法作用域
counter5=counter(5)
print(counter5())
print(counter5())
print(counter5())
print(counter(5)())
print(counter(5)())
print(counter(5)())
print(counter5())
print(counter5())
print(counter5())
print(counter5)
# 查看内存正在被几个地方引用
print(sys.getrefcount(counter))
# 闭包的应用,直线函数的参数设定+自变量设定
def line(a,b):
    def calcu(x):
        return a*x+b
    return calcu
line1=line(2,1)
line2=line(3,2)
print('21------',line1(3))
print('22------',line1(7))
print('23------',line2(3))
print('24------',line2(7))

28、闭包之上-装饰器

# 手写闭包装饰器(ps:变量作用4大范围-LEGB规则-Local,Enclosing,Global,Built_in)
def timer(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        start=time.time()
        result=func(*args,**kwargs)
        end=time.time()
        print(f'函数耗时{end-start}s')
        return result
    return wrapper

@timer
def sleep3(x):
    time.sleep(3)
    return x**3

print('1------',sleep3(4))
# 手写高级闭包装饰器-闭包嵌套更多的函数
def timer_author(author):
    def timer(func):
        @functools.wraps(func)
        def wrapper(*args,**kwargs):
            start=time.time()
            result=func(*args,**kwargs)
            end=time.time()
            print(f'高级闭包装饰器记录的耗时是{end-start}s,且设置者是{author}')
            return result
        return wrapper
    return timer

@timer_author('刘源')
def sleep2():
    time.sleep(2)
    return '2秒'

@timer_author('李昊')
def sleep4():
    time.sleep(4)
    return '4秒'

print('2------',sleep2())
print('3------',sleep4())

29、上下文管理器

# 上下文管理器,自动关闭文件,自动处理文件冲突
with open('LinuxPython5W2H-12.txt','a') as f:
    f.write(f'{__file__}运行记录:')
    f.write(time.ctime())
    f.write('---'+str(time.time())+'\n')

30、类和对象的复习

# 类和对象
class Player():
    """玩家类"""
    def __init__(self, name, hp,job):
        # __name是表示,不可修改
        self.__name = name
        self.hp = hp
        self.job = job
    def print_role(self,confidence=100):
        print(f'姓名:{self.__name},血量:{self.hp},自信心:{confidence},职业:{self.job}')

class Monster():
    """怪物类"""
    def __init__(self,hp=60):
        self.hp=hp
    def run(self):
        print('移动到某个位置')
    def whoami(self):
        print('我是所有怪物的母亲')

class Animal(Monster):
    '普通怪物'
    def __init__(self,hp=10):
        super().__init__(hp)

class Boss(Monster):
    """Boss类怪物"""
    def __init__(self,hp=100):
        super().__init__(hp)
    def whoami(self):
        print('我是boss级怪物')
a1=Monster()
print(f'a1的类型:{type(a1)}',f'是Monster的子类吗:{isinstance(a1,Monster)}')
a1.whoami()
a2=Animal(30)
print(f'a2的类型:{type(a2)}',f'是Monster的子类吗:{isinstance(a2,Monster)}')
a2.run()
a3=Boss()
print(f'a3的类型:{type(a3)}',f'是Monster的子类吗:{isinstance(a3,Monster)}')
a3.whoami()
print('1------',a3.hp)

31、多进程多线程练习记录

# coding=utf-8
# encoding: utf-8
"""
Author:刘源
Createtime:2021/08/01 01:04:19
Updatetime:2021/08/01 01:04:19
Description:多线程
"""
import time, threading, os, pathlib, multiprocessing, sys, codecs, re, functools, sys, pytest

# 上下文管理器,自动关闭文件,自动处理文件冲突
with open('tt15.txt', 'a') as f:
    f.write(f'{__file__}运行记录:')
    f.write(time.ctime())
    f.write('---' + str(time.time()) + '\n')
    print(sys.path)


# 使用标准库的线程类
def myThread(time1):
    print(f'线程开始:{time.ctime()},将休眠{time1}s,线程信息{threading.current_thread()}.{threading.current_thread().getName()}')
    time.sleep(time1)
    print(f'线程结束:{time.ctime()},已休眠{time1}s,线程信息{threading.current_thread()}.{threading.current_thread().getName()}')


a = []
a.append(threading.Thread(target=myThread, name='子线程1', args=(9,)))
a.append(threading.Thread(target=myThread, kwargs={"time1": 7}, name='子线程2'))
a.append(threading.Thread(target=myThread, name='子线程3', args=(5,)))
a.append(threading.Thread(target=myThread, args=(3,)))
for t in a:
    t.start()
    t.join()
    time.sleep(0.5)
a.append(threading.Thread(target=myThread, args=(4,)))
myThread(2)


# 自己重写线程类run方法
class t(threading.Thread):
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, daemon=None, time1=9):
        super().__init__(group, target, name, args, kwargs)
        self.time1 = time1

    def run(self):
        print(
            f'线程开始:{time.ctime()},将休眠{self.time1}s,线程信息{threading.current_thread()}.{threading.current_thread().getName()}')
        time.sleep(self.time1)
        print(
            f'线程结束:{time.ctime()},已休眠{self.time1}s,线程信息{threading.current_thread()}.{threading.current_thread().getName()}')


b = []
b.append(t(target=myThread, args=(9,), time1=9))
b.append(t(target=myThread, kwargs={"time1": 7}, time1=7))
b.append(t(target=myThread, args=(5,), time1=5))
b.append(t(target=myThread, args=(3,), time1=3))
for t in b:
    t.start()
    time.sleep(0.5)

32、多线程模拟生产者消费者问题

import time, threading, os, pathlib, multiprocessing, sys, codecs, re, functools, sys, pytest,random,queue
# 上下文管理器,自动关闭文件,自动处理文件冲突
with open('tt16.txt', 'a') as f:
    f.write(f'{__file__}运行记录:')
    f.write(time.ctime())
    f.write('---' + str(time.time()) + '\n')
    print(sys.path)

queue1=queue.Queue(5)
class ProducerThread(threading.Thread):
    """生产者子线程类"""
    def run(self):
        name=threading.current_thread().getName()
        global queue1
        while True:
            product=random.randint(1,99)
            queue1.put(product)
            print(f'生产者{name}生产了{product}个数据')
            rest=random.randint(1,5)
            time.sleep(rest)
            print(f'生产者{name}休眠了{rest}秒')

class ConsumerThread(threading.Thread):
    """消费者子线程类"""
    def run(self):
        name=threading.current_thread().getName()
        global queue1
        while True:
            product=queue1.get()
            queue1.task_done()
            print(f'消费者{name}消费了{product}个数据')
            rest=random.randint(1,5)
            time.sleep(rest)
            print(f'消费者{name}休眠了{rest}秒')

p1=ProducerThread(name='p1')
p1.start()
c1=ConsumerThread(name='c1')
c1.start()

33、re正则表达式练习记录

import time, threading, os, pathlib, multiprocessing, sys, codecs, re, functools, sys, pytest,random,queue
# 上下文管理器,自动关闭文件,自动处理文件冲突
with open('tt17.txt', 'a') as f:
    f.write(f'{__file__}运行记录:')
    f.write(time.ctime())
    f.write('---' + str(time.time()) + '\n')
    print(sys.path)
# re.compile().match()匹配开头
print('1------',re.compile('cat').match('cat123'),re.compile('cat').match('123cat123'))
# re.compile().fullmatch()匹配全部
print('2------',re.compile('cat').fullmatch('cat123'),re.compile('\d{3}cat\d*').fullmatch('123cat1234'))
# re.compile().search()匹配任意
print('3------',re.compile('cat').search('123cat456'),re.compile('cat').search('123caat456'))
# .任意非空、非space的单字符
print('4------',re.compile('ca..t').search('123ca12t456'))
# *将前一个字符重复任意次(0次与多次),+将前一个字符重复至少1次,?出现一次或不出现
print('5------',re.compile('ca.*t').search('1cat4'),re.compile('ca.*t').search('1ca5t4'))
print('6------',re.compile('ca.+t').search('1caaat4'),re.compile('ca.+t').search('1cat4'))
print('7------',re.compile('ca.?t').search('1cat4'),re.compile('ca.?t').search('1ca1t4'),re.compile('ca.?t').search('1ca12t4'))
# ^开头限定,$结尾限定
print('8------',re.compile('^cat').search('cat4h'),re.compile('^cat').search('ycat4h'))
print('9------',re.compile('cat$').search('ttcat'),re.compile('^cat').search('ttcat4'))
#{m}出现m次,{m,n}出现[m,n]次,{m,}至少出现m次
print('10------',re.compile('ca{2}t').search('1caat2'),re.compile('ca{2}t').search('1cat2'),re.compile('ca{2}t').search('1caaat2'))
print('11------',re.compile('ca{2,3}t').search('1caat2'),re.compile('ca{2,3}t').search('1caaat2'),re.compile('ca{2,3}t').search('1cat2'))
print('12------',re.compile('ca{2,}t').search('1cat2'),re.compile('ca{2,}t').search('1caat2'),re.compile('^ca{2,}t').search('caaat27'))
# [abc]只匹配枚举的字符(范围写法:[1-9],[a-z])
print('13------',re.compile('c[abc]t').search('1cbt2'),re.compile('c[abc]t').search('cdt'),re.compile('c[1-9]t').search('c6t'))
# | 左边整体或右边整体
print('14------',re.compile('c[abc]|5t').search('1cbjj2'),re.compile('c[abc]|5t').search('1c995t2y'),re.compile('c[abc]|5t').search('1cht2'))
# \s 任意单空白符,等价于 [\t\n\r\f\v],\S 任意非空白符
print('15------',re.compile('c\st').search('1c th'),re.compile('c\s+t').search('1c   tu'),re.compile('c\st').search('1ctu'))
# \d 数字单字符,同[123456789]=[1-9]=\d
print('16------',re.compile('c\dt').search('1c5th'),re.compile('c\dt').search('1c57th'),re.compile('c\d{3,}t').search('1c5778th'))
# \D 非数字单字符
print('17------',re.compile('c\Dt').search('1c5th'),re.compile(r'c\Dt').search('1c-th'))
# ()用于分组,\数字 分组引用
print('18------',re.compile(r'(cat)\1').search('catcat'))
# | 左边整体或右边整体
print('19------',re.compile(r'c(123|456)t').search('c123t'),re.compile(r'c(123|456)t').search('c456t'),re.compile(r'c(123|456)t').search('c123456t'))
# .*? 不使用贪婪模式 (无问号则会贪婪匹配)
print('20------',re.compile(r'cat.*?').search('cat123'),re.compile(r'cat.*').search('cat123'),re.compile(r'cat.*?').search('cat'))
# 小玩法,年月日1
print('21------',re.compile(r'\d{4}-\d{2}-\d{2}').search('2021-08-01'))
# 小玩法,年月日2
print('22------',re.compile(r'\d+-\d+-\d+').search('2021-08-01'))
# 分组后取出
print('23------',re.compile(r'(\d+)-(\d+)-(\d+)').search('2021-08-01').group(1))
print('24------',re.compile(r'(\d+)-(\d+)-(\d+)').search('2021-08-01').group(2))
print('25------',re.compile(r'(\d+)-(\d+)-(\d+)').search('2021-08-01').group(3))
print('26------',re.compile(r'(\d+)-(\d+)-(\d+)').search('2021-08-01---2021-08-02').groups())
# sub正则替换
print('27------',re.compile(r'#.*?').sub('','cat#123gdfg!@#'),re.compile(r'#.*$').sub('','cat#123gdfg!@#'))
# replace普通替换
print('28------','cat#123'.replace('#123',''))
# \w	匹配单个字母数字及下划线
print('29------',re.compile(r'(cat\w)\1').search('cat_cat_'),re.compile(r'(cat\w)\1').search('cat_cat%'))
# \W	匹配单个非字母数字及下划线
print('30------',re.compile(r'(cat\W)\1').search('cat@cat@'),re.compile(r'(cat\W)\1').search('cat@cat%'),re.compile(r'(cat\W)\1').search('cat%cat%'))
# findall匹配多个
print('31------',re.compile(r'(cat\W)\1').findall('cat@cat@cat@cat@cat@cat@cat@'))
print('32------',re.compile(r'(cat\w)\1').findall('cat1cat1cat2cat2cat3cat3'))

在这里插入图片描述
34、时间标准库time,datetime,数学标准库math,random,练习记录

# coding=utf-8
# encoding: utf-8
"""
Author:刘源
Createtime:2021/08/01 17:55:21
Updatetime:2021/08/01 17:55:21
Description:时间标准库time,datetime,数学标准库math,random
"""
import time, threading, os, pathlib, multiprocessing, sys, codecs, re, functools, sys, pytest,random,queue,datetime
# 上下文管理器,自动关闭文件,自动处理文件冲突
with open('tt18.txt', 'a') as f:
    f.write(f'{__file__}运行记录:')
    f.write(time.ctime())
    f.write('---' + str(time.time()) + '\n')
    print(sys.path)
print('1------',time.time())
print('2------',time.ctime())
print('3------',time.localtime())
print('4------',time.strftime('%Y/%m/%d %H:%M:%S'))
print('5------',datetime.datetime.now())
# 'delta-希腊字母,数学物理学中表示变量、增量'
print('6------',datetime.datetime.now()+datetime.timedelta(days=365))
print('7------',datetime.datetime(2021,8,1,18,27,20)+datetime.timedelta(days=365))
print('8------',random.randint(-9,9),random.randint(-9,9),random.randint(-9,9))
print('9------',random.random(),random.random(),random.random(),random.random())
print('10------',random.choice(list(i for i in range(8))))
print('11------',random.choice('abc123ABC'),random.choice('abc123ABC'),random.choice('abc123ABC'),random.choice('abc123ABC'))
print('12------',random.choice(['a','1','@']),random.choice(('a','1','@')))

35、os.path,pathlib.Path练习记录

# coding=utf-8
# encoding: utf-8
"""
Author:刘源
Createtime:2021/08/01 18:56:36
Updatetime:2021/08/01 18:56:36
Description: os.path,pathlib.Path
"""
import time, threading,os, multiprocessing, sys, codecs, re, functools, sys, pytest,random,queue,datetime,pathlib
# 上下文管理器,自动关闭文件,自动处理文件冲突
with open('tt19.txt', 'a') as f:
    f.write(f'{__file__}运行记录:')
    f.write(time.ctime())
    f.write('---' + str(time.time()) + '\n')
    print(sys.path)
# os
print('1------',os.path.abspath(''))
print('2------',os.path.abspath('.'))
print('3------',os.path.abspath('..'))
print('4------',os.path.abspath(__file__))
print('5------',os.path.exists('tt19.py'))
print('6------',os.path.exists('./tt19.py'))
print('7------',os.path.exists('../tt19.py'))
print('8------',os.path.isfile('./tt19.py'))
print('9------',os.path.isdir('./tt19.py'))
print('10------',os.path.isfile('./tttttt.py'))
print('11------',os.path.isdir('./threeState'))
print('12------',os.path.dirname(__file__))
print('13------',os.path.basename(__file__))
print('14------',os.path.split(__file__))
print('15------',os.path.join(os.path.dirname(__file__),'不存在的.txt'))
print('16------',os.getcwd())
# pathlib
print('17------',pathlib.Path(),pathlib.Path().resolve())
print('18------',pathlib.Path('.').resolve(),pathlib.Path().is_dir(),pathlib.Path().is_file())
print('19------',pathlib.Path('threeState').is_dir(),pathlib.Path('threeState').is_file())
if not pathlib.Path('./pathlib/tt1.txt').exists():
    pathlib.Path('./pathlib/tt1.txt').mkdir(parents=True)
print('20------',pathlib.Path('./pathlib/tt1.txt').is_file(),pathlib.Path('./pathlib/tt1.txt').is_dir())

36、pip安装

# 安装pip
python -m ensurepip
# 更新pip
python -m pip install --upgrade pip 

37、根据起点、终点、间隔值,生成一个由重多子列表作为元素的大列表对象

def listOut(start, end, sep):
    """
    根据起点、终点、间隔值,生成一个由重多子列表作为元素的大列表对象
    :param start: int,起点
    :param end:  int,终点,必须大于等于起点
    :param sep: int,必须大于0
    :return:
    """
    a = []
    for i in range(start, end + 1, sep):
        a.append(list(k for k in range(i, i + sep) if k < end + 1))
    print(a)

listOut(-2, 20, 5)
listOut(-25, 32, 10)
listOut(1, 1, 1)
listOut(1, 7, 1)
listOut(1, 4, 3)

效果:
在这里插入图片描述
38、多维数组的排序
在这里插入图片描述
39、列表方法操练
在这里插入图片描述
40、字符串方法操练
在这里插入图片描述
41、字典方法操练
在这里插入图片描述
42、简单的os操作
在这里插入图片描述
43、python中的队列初探
在这里插入图片描述

  • 39
    点赞
  • 145
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天道哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值