1、编程计算两个日期之间的天数与周数
dateutil模块主要有两个函数,parser和rrule。
其中parser是根据字符串解析成datetime,而rrule则是根据定义的规则来生成datetime。
1 importdatetime2 from dateutil importrrule3
4 classBetweenDate:5 def __init__(self,start,stop):6 self.start = datetime.datetime.strptime(start,"%Y,%m,%d")7 self.stop = datetime.datetime.strptime(stop,"%Y,%m,%d")8 defBetdays(self):9 d = rrule.rrule(rrule.DAILY,dtstart=self.start,until=self.stop).count()10 return d if d > 0 elseFalse11 defBetweeks(self):12 w = rrule.rrule(rrule.WEEKLY,dtstart=self.start,until=self.stop).count()13 return w if w > 0 elseFalse14
15 time = BetweenDate('2020,1,14','2020,7,17')16 days =time.Betdays()17 weeks =time.Betweeks()18 print('日期间隔天数:',days)19 print('日期间隔周数:',weeks)20
21 结果:22 日期间隔天数: 186
23 日期间隔周数: 27
View Code
time模块操作归纳
操作
作用
例子
time.time()
打印当前时间(结果为浮点数)
a = time.time()
结果:1595468499.5463095
time.localtime()
浮点数--->时间结构体
b=time.localtime(a)
结果:time.struct_time(tm_year=2020, tm_mon=7, tm_mday=23, tm_hour=9, tm_min=43, tm_sec=7, tm_wday=3, tm_yday=205, tm_isdst=0)
time.asctime()
时间结构体--->时间字符串
c=time.asctime(b)
结果:'Thu Jul 23 09:43:07 2020'
time.strftime()
时间结构体--->指定格式时间字符串
d=time.strftime("%Y-%m-%d %H:%M:%S",b)
结果:'2020-07-23 09:43:07'
time.strptime()
时间字符串--->时间结构体
e=time.strptime(d,"%Y-%m-%d %H:%M:%S")
结果:time.struct_time(tm_year=2020, tm_mon=7, tm_mday=23, tm_hour=9, tm_min=43, tm_sec=7, tm_wday=3, tm_yday=205, tm_isdst=-1)
对于结构体中元素的说明:
tm_year:年
tm_mon:月
tm_mday:日
tm_hour:小时
tm_min:分
tm_sec:秒
tm_yday:一周中的索引([0,6],周一的索引是0)
tm_day:一年中的索引([1,366])
tm_isdist:1 if summer time is in effect, 0 if not, and -1 if unknown
2、编写程序用于判断学生的作业是否做完
1 classStudent:2 def __init__(self,name,grade,subject):3 self.name =name4 self.grade =grade5 self.subject =subject6 defdo_work(self,time):7 if self.grade>3 and time > 2:8 returnTrue9 elif self.grade<3 and time < 0.5:10 returnTrue11 else:12 returnFalse13 classTeacher:14 def __init__(self,name,subject):15 self.name =name16 self.subject =subject17 defevaluate(self,result):18 ifresult:19 return "You are great."
20 else:21 return "You sholud work hard!"
22
23 stu_zhangshan = Student('zhangshan',5,'math')24 tea_wang = Teacher('wang','math')25 resu = stu_zhangshan.do_work(1)26 tea_said =tea_wang.evaluate(resu)27 print(tea_said)28
29 结果:30 You sholud work hard!
View Code
3、筛选素数
1 importmath2 defis_prime(m):3 if m<=1:4 return '不是素数'
5 for i in range(2,int(math.sqrt(m))+1):6 if m%i==0:7 return '不是素数'
8 return '素数'
9
10 def choice_prime(*args):11 primes = [i for i in args if is_prime(i)=='素数']12 returnprimes13
14 print(choice_prime(1,2,3,4,5,6,7,8,9))15
16 结果:17 [2, 3, 5, 7]
View Code
4、使用函数求斐波那切数列
1 deffibs(n):2 result=[0,1]3 for i in range(n-2):#由于数列前两项已知,故只需求后n-2项即可
4 result.append(result[-1]+result[-2])5 returnresult6
7 print(fibs(10))8
9 结果:10 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
View Code
使用类和迭代器实现斐波那切数列
1 #使用类和迭代器实现斐波那切数列
2 classFibs():3 def __init__(self,max):4 self.max =max5 self.a =06 self.b = 1
7 def __iter__(self):8 returnself9 def __next__(self):10 fib =self.a11 if fib >self.max:12 raiseStopIteration13 else:14 self.b, self.a = self.a +self.b, self.b15 returnfib16
17 fibs = Fibs(100000) #不会占用太多内存空间
18 lst = [fibs.__next__() for i in range(10)]19 print(lst)20 '''
21 结果:22 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]23 '''
View Code
使用生成器实现斐波那切数列
1 deffibs():2 a,b = 0,1
3 whileTrue:4 yielda5 b,a = a +b, b6 #生成一个生成器
7 f = fibs() #此时已经无限多个菲波那切数列预存到生成器,使用时将所需的元素督导内存即可
8
9 importitertools10 lst = list(itertools.islice(f,10))11 print(lst)12
13 '''
14 结果:15 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]16 '''
View Code
5、输入字符串,转成成数字形式求和
eval("34-23") #结果:11
1 s='44+ 34'
2 s=s.strip().split('+')3 print(s)4 n=05 for i ins:6 n=n+int(i)7 print(n)8
9 结果:10 ['44', '34']11 78
View Code
6、对输入的字母大小写进行变换,即小写转大写,大写转小写
list-->str用join()
str-->list表用split()
1 deffun(s):2 #l = []
3 #for i in s:
4 #if i == i.upper():
5 #l.append(i.lower())
6 #else:
7 #l.append(i.upper())
8 l = [i.lower() if i==i.upper() else i.upper() for i ins]9 return "".join(l)10
11 print(fun('Hello'))12
13 结果:14 hELLO
View Code
与'Hello'.swapcase()作用类似,可参见字符串的基本内容
7、提取字符串中的所有元音字母
a = ord('a') #结果:97
b = chr(97) #结果:a
1 classKeeper:2 def __init__(self,keep):3 self.keep =set(map(ord,keep))4 def __getitem__(self,n):5 if n not inself.keep:6 returnNone7 else:8 returnchr(n)9 def __call__(self,a):10 returna.translate(self)11
12 vowels = Keeper("aeiou")13 result = vowels("Cherry is beautiful!")14 print(result) #结果:'eieauiu'
View Code
8、年、月的日历图,并判断是否为闰年
1 importcalendar2 from datetime importdate3 mydate = date.today() #结果:datetime.date(2020, 7, 22)
4 print(calendar.calendar(2020)) #打印年的日历图
5 print(calendar.month(mydate.year,mydate.month)) #打印月的日历图
6
7 结果:8 年的日历图:9 2020
10
11 January February March12 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su13 1 2 3 4 5 1 2 1
14 6 7 8 9 10 11 12 3 4 5 6 7 8 9 2 3 4 5 6 7 8
15 13 14 15 16 17 18 19 10 11 12 13 14 15 16 9 10 11 12 13 14 15
16 20 21 22 23 24 25 26 17 18 19 20 21 22 23 16 17 18 19 20 21 22
17 27 28 29 30 31 24 25 26 27 28 29 23 24 25 26 27 28 29
18 30 31
19
20 April May June21 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su22 1 2 3 4 5 1 2 3 1 2 3 4 5 6 7
23 6 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13 14
24 13 14 15 16 17 18 19 11 12 13 14 15 16 17 15 16 17 18 19 20 21
25 20 21 22 23 24 25 26 18 19 20 21 22 23 24 22 23 24 25 26 27 28
26 27 28 29 30 25 26 27 28 29 30 31 29 30
27
28 July August September29 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su30 1 2 3 4 5 1 2 1 2 3 4 5 6
31 6 7 8 9 10 11 12 3 4 5 6 7 8 9 7 8 9 10 11 12 13
32 13 14 15 16 17 18 19 10 11 12 13 14 15 16 14 15 16 17 18 19 20
33 20 21 22 23 24 25 26 17 18 19 20 21 22 23 21 22 23 24 25 26 27
34 27 28 29 30 31 24 25 26 27 28 29 30 28 29 30
35 31
36
37 October November December38 Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su39 1 2 3 4 1 1 2 3 4 5 6
40 5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13
41 12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20
42 19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27
43 26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31
44 30
45
46
47 月的日历图:48 July 2020
49 Mo Tu We Th Fr Sa Su50 1 2 3 4 5
51 6 7 8 9 10 11 12
52 13 14 15 16 17 18 19
53 20 21 22 23 24 25 26
54 27 28 29 30 31
View Code
判断是否是闰年
1 importcalendar2 from datetime importdate3 mydate = date.today() #结果:datetime.date(2020, 7, 22)
4 is_leap =calendar.isleap(mydate.year)5 print(("{}是闰年" if is_leap else "{}不是闰年").format(mydate.year))6
7 结果:8 2020是闰年
View Code
9、创建数据字典的3中方法
1 dict(a='1',b='2')2
3 dict(zip(['a','b'],[1,2]))4
5 dict([('a',1),('b',2)])6
7 结果:{'a': 1, 'b': 2}
View Code
10、创建不可修改的集合
1 a = [1,4,2,3,1]2 a_set =set(a)3 a_frozenset =frozenset(a)4 print(a_set) #结果:{1, 2, 3, 4}
5 print(a_frozenst) #结果:frozenset({1, 2, 3, 4})
6
7 #增加--add()、update()
8 print(a_set.add(13) ) #结果:{1, 2, 3, 4, 13}
9 print(a_set.update('hello')) #结果:{1, 2, 3, 4, 'e', 'h', 'l', 'o'}
10
11 #删除--remove()、“-=”
12 print(a_set.remove('h')) #结果:{1, 2, 3, 4, 'e', 'l', 'o'}
13 print(a_set -= set('elo')) #结果:{1, 2, 3, 4}
14
15 #删除集合
16 del a_set
View Code
11、同时做幂、余运算
pow()的三个参数全部给出时表示先进行幂运算在进行取余运算
1 print(pow(3,3)) #结果:9
2 print(pow(3,3,4)) #结果:1
View Code
12、查看变量所占字节数
1 importsys2 a = [1,4,2,3,1]3 print(sys.getsizeof(a)) #结果:104
View Code
13、排序函数
默认升序排列,reverse = True表示降序排列
1 a = [1,4,2,3,1]2 print(sorted(a,reverse=True)) #结果:[4, 3, 2, 1, 1]
3
4 b = [{'name':'xiaoming','age':18,'gender':'male'},5 {'name':'xiaohong','age':20,'gender':'female'}]6 #按照age的降序排列
7 print(sorted(b,key =lambda x:x['age'],reverse=True))8
9 结果:10 [{'name': 'xiaohong', 'age': 20, 'gender': 'female'}, {'name': 'xiaoming', 'age': 18, 'gender': 'male'}]
View Code
14、判断真假
(1)all---->如果可迭代对象元素全为真,返回True,否则返会False
(2)any--->可接受一个可迭代对象,如果迭代对象里至少有一个元素为真,就返回True
1 print(bool(0)) #结果:False
2 print(all([0,1,2,3])) #结果:False
3 print(any([0,1,2,3])) #结果:True
View Code
15、字符串格式化
1 print("I am {0},age {1}".format('Cherry','18'))#结果:I am Cherry,age 18
2
3 #保留小数点后两位
4 print("{:.2f}".format(3.1415926)) #结果:3.14
5
6 #带符号保留小数点后两位
7 print("{:+.2f}".format(-1)) #结果:3-1.00
8
9 #不带小数位
10 print("{:.0f}".format(9.5678)) #结果:10
11
12 #以整数进行补0,在左边进行填充,其宽度为4---->可改变填充方向以及宽度
13 print("{:0>3d}".format(7)) #结果:007
14
15 #以逗号的形式分割数字字符
16 print("{:,}".format(9876543210)) #结果:9,876,543,210
17
18 #指数计数
19 print("{:2e}".format(9876543210)) #结果:9.876543e+09
20
21 #百分比格式
22 print("{:.2%}".format(0.678)) #结果:67.800%
View Code
16、读写文件
1 #打开文件
2 importos3 os.chdir('C:\\Users\\xhl\\Desktop\\ww')4 print(os.listdir()) #结果:['a.txt']
5
6
7 #读文件
8 with open('a.txt',mode='r',encoding='utf8') as f:9 o =f.read()10 print(o)11 结果:数据放好多假货常委会发货单黄齑淡饭就很好父亲和如何按厚度复活甲横槊赋诗12
13
14 #写文件
15 with open('new_file.csv',mode='w',encoding='utf8') as f:16 w = f.write('I love python\nI am beautiful')17 print(os.listdir()) #结果:['a.txt', 'new_file.csv']
18
19 with open('new_file.csv',mode='r',encoding='utf8') as f:20 print(f.read())21 #结果:
22 I love python23 I am beautiful
View Code
mode取值表
'r'
读取(默认情况)
'w'
写入,并先截断文件
'x'
排它性创建,如果文件已存在则失效
'a'
写入,如果文件存在则在末尾追加
'b'
二进制模式
't'
文本模式(默认情况)
'+'
打开用于更新(读取与写入)
17、链式操作
1 from operator importadd,sub2 defadd_or_sub(a,b,oper):3 return (add if oper=="+" elsesub)(a,b)4 print(add_or_sub(3,4,'+')) #结果:7
View Code
18、提取文件后缀名、完整文件名
os.path.splitext()---->提取文件后缀名
os.path.split()---->提取完整文件名
其结果是tuple类型
1 #提取后缀名
2 importos3 os.chdir('C:\\Users\\xhl\\Desktop\\ww') #结果:['a.txt', 'new_file.csv']
4 print(os.path.splitext('C:\\Users\\xhl\\Desktop\\ww\\a.txt'))5 #结果:('C:\\Users\\xhl\\Desktop\\ww\\a', '.txt')
6
7 #提取完整文件名
8 print(os.path.split('C:\\Users\\xhl\\Desktop\\ww\\a.txt')[-1])9 #结果:'a.txt'
View Code
19、将list等分成n组
ceil()--->向上舍入最为最接近的函数
1 from math importceil2 defdivide_iter(lst,n):3 if n<=0:4 yieldlst5 return
6 i,div = 0, ceil(len(lst)/n)7 while i<8 yield lst i>
10
11 for group in divide_iter([1,2,3,4,5,6,7],3):12 print(group)13
14 结果:15 [1, 2, 3]16 [4, 5, 6]17 [7]
View Code
20、python常用操作符总结(好用易忽略)
符号
用途
例子
/
返回浮点数
8/5--->1.6
//
返回两数相除的整除部分
8/5--->1
%
返回两数相除的余数
8%5--->3
**
计算几次方
2*3--->8
_
交互模式下,上一次打印的表达式的值被赋值给变量_
2+3---->5
_+3---->8
““
打印串时无需转义字符
print("I'm a boy")
结果:I'm a boy
''
打印串时需转义字符
print('I\'m a boy')
结果:I'm a boy
一对双引号:
即"""或'''
跨行自动连续输入字符串
print("""yiduhdsjhjdj
hhhhhhhhhhhh""")
结果:yiduhdsjhjdj
hhhhhhhhhhhh
8>