-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython.txt
More file actions
640 lines (540 loc) · 15.7 KB
/
Copy pathpython.txt
File metadata and controls
640 lines (540 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
数据类型:
1.数字 price=2.50
bin(val) 二进制
oct(val) 八进制
hex(val) 十六进制
2.字符串 name="zhangsan"
3.列表 list=["python","java","c++","c#"]
append(element)
extend(List)
insert(i,element)
remove(element)
pop(index)
clear()
index(element)
count(element)
sort()
reverse() 倒序
列表推导式
list = []
list = [(x,y) for x in [1,2,3] for y in [4,5,6] if x!=y ]
4.元组 ta = (404,"page not found")
5.字典 dic = {'name':'zhangsan','age':20}
dic.get(key)
dic.items()
dic.keys()
dic.values()
6.对象 obj
7.集合 s = set() s={}
add(element)
pop()
clear()
update()
difference(Set) -操作
intersection(Set) &操作
union(Set) |操作
symmetric_difference(Set) ^操作
变量作用域
class def lambda会引入新的作用域
global 局部修改全局变量
nolocal 闭包修改自由环境变量
迭代器
iter() 获取迭代器
next(iter) 获取下一个元素 过界StopIteration异常
生成器
1.
list = [2*x for x in range(3)] 推导式
gen = (2*x for x in range(3)) 生成器 gen是一个迭代器
2.
def fun()
yield 1
yield 2
yield 3
输出:
print('r=%d' % r)
格式化
capitalize(word)
center(width,str)
count(str,begin,end)
endswith(suffix,begin,end)
expandtabs(tabsize) tab转空格
find(str,begin,end)
index(str,begin,end)
isalnum() 是否字母或数字
istitle()
join(seq) 链接seq中所有元素
ljoin(width [,fillchar]) 原串左对齐直接字符到指定长度 str.ljust(20,'#')
rjoin(width [,fillchar])
split(str[, len]);
输入输出
f = open(文件名,模式,encoding="utf-8")
f.readline()
f.readlines()
f.read(2)
...
f.write()
...
f.seek(offset) 移动指针
with open("text.txt") as f:
f.read()
自动关闭文件
文件模式
http://www.runoob.com/python/python-files-io.html
函数
必需参数
关键字传参
默认参数 def fun(p='default'):
不定长参数 def fun(*args):
成员运算
in
not in
身份运算
不可变对象:
数字
字符串
元组
is ==
is not
序列函数:
工厂函数
list(iter)
tuple(iter)
操作函数
len(list)
max(list,lambda)
min(list,lambda)
sum(list) 数值求和
zip()
sorted(list,lambda)
reversed(list) 返回逆向迭代器
enumerate(iter) 返回索引,元素===>>>
=====================================
for i,ite in enumerate(list):
print(i, ite);
=====================================
e = enumerate(list)
print(e.__next__())
常用函数:
abs()
pow()
round()
min()
max()
sum()
模块 math
pi
e
floor()
ceil()
pow(x,y)
sqrt(x)
exp(x) e^x
trunc()
模块 random
isinstance(变量,变量类型(int/float/str...))判断数据类型
assert 判断条件
len(求长度的对象)
range([start,]stop[,step]) ==>> range(0,stop,1); for i in range(10)
array.append(ele) 向集合添加元素
array.extend(arr) 向集合添加多个元素
字典
dic1 = {"aa":"aaaa","bb":"bbbb","cc":"ccccc"}
dic2 = dict(aa="aaaaa",bb="bbbbb",cc="cccccc")
dic3 = dict((("aa","aaa"),("vv","vvvvvv"),("nn","nnnnn")))
dic3["mm"]="mmmm"
dic4 = dic4.fromkeys((1,2,3),"val")
for item in dic4.items():
print(item)
导入模块:
import easygui
from easygui import *
import easygui as g
一般模块不让以数字开头,如果以数字开头导入需要importlib模块
例:=============================================
import importlib
别名 = importlib.import_module(模块名)
if __name__ == "__main__":
如果方件单独执行将被调用,如果import的方式将不会被执行
模块的搜索路径和存储:
系统默认的模块搜索路径有:
import sys
sys.path 可以打印所有搜索的路径列表
sys.path.append(dir) 添加搜索路径
搜索顺序:
1.内存中已经存在的模块
2.python内置模块
3.搜索sys.path
包:
/--包
/--/-- __init__.py
/--/-- 模块1
/--/-- 模块2...
/--/-- 子包
导包 与导入模块一致
import package_name
import package_name as rename
import package_name.module_name
import package_name.module_ame as rename
from package_name import module1_name module2_name...
这种导入操作不执行__init__内容
from package_name import *
在使用这种语法的时候,*可以导入的内容:
__init__.py中没有__all__,那么只可以把__init__.py中的内容导入
如果设置了__all__的值,那么将按照__all__指定的子包或者模块导入
常用模块:
calendar
calendarcalendar(2018) 获取2018的日历字符串
calendar.isleap(2018) 判断是否闰年
calendar.leapdays(1998,2018) 年份之间闰年的个数
calendar.month(2018,4) 获取2018-3日历字符串
calendar.monthrange(2018,4) 获取2018-4从周几天始0表示周一,共天数
calendar.monthcalendar(2018,4) 打印日历距阵
calendar.prcal(2018) 直接打印日历
calendar.weekday(2018,4,11) 获取周几
time
时间元组
索引 内容 属性
0 年 tm_year
1 月 tm_mon
2 日 tm_mday
3 时 tm_hour
4 分 tm_min
5 秒 tm_sec
6 周几 tm_wday
7 年第天 tm_yday
8 夏令时 tm_isdst
time.timezone 系统时钟时区,返回间隔秒
time.time() 返回时间戳
time.localtime() 返回时间元组
time.asctime(time.localtime()) 'Wed Apr 11 15:13:15 2018'
time.mktime(time.localtime()) 结构化时间转时间戳
time.sleep(n) 睡眠n秒
time.strftime("%Y-%m-%d %H:%M" ,time.localtime()) 格式化时间
datetime
timeit
os
shutil
zip
math
string
pickle模块
my_list = []
pickle_file = open("my_list.pkl","wb")
pickle.dump(my_list,pickle_file)
pickle.close()
pickle_file = open("my_list.pkl","rb")
my_list1 = pickle.load(pickle_file)
pickle.close()
condition 非0 非None 非空为真
if condition1:
statement_block1
elif condigion2:
statement_block2
else:
statement_block3
异常处理
try:
语句
except Exception as reason:
异常执行
finally:
终将执行
else
没有异常将执行
else语句
while 条件:
循环体
else:
顺利执行完循环体将执行
常见错误
SyntaxError 语法错误
NameError
ZeroDivisionError 零除错误
IndexError 索引错误
ValueError
ModuleNotFoundError
ImportError
with open("data.txt","w") as f
文件不用时将自动close()
继承:
class myList(list)
封装
默认公有
私有
__name Python重命名为:实例._类名_字段名
self.__字段名
例:
class Ball:
def __init__(self,name = "球"):
self.__name = name
def setName(self,name):
self.__name = name
def getName():
return self.__name
def kick(self):
print("我是%s,该死的,谁踢我!" % self.__name)
a = Ball("土豆")
a._Ball__name = "大土豆"
a.kick()
继承,支持多继承
class Parent:
def __init__(self,age=0):
self.age = age
def hello(self):
print("正在调用父类方法")
class Child(Parent):
def __init__(self,name):
super().__init__(21)
## Parent.__init__(self,20)
self.name = name
def hello(self):
print("我是%s,年龄%d,正在调用子类方法" % (self.name,self.age))
a = Child("土豆")
a.hello()
迭代器
iter()
next()
dic = {"aa":"aaaaaaa",\
"bb":"bbbbbbbb",\
"cc":"cccccccccc"
}
for e in dic:
print("%s == %s" % (e,dic[e]))
it = iter(dic)
for i in range(len(dic)):
print(next(it))
__iter__()
__next__()
class Fibs:
def __init__(self,max):
self.a = 0
self.b = 1
self.max = max
def __iter__(self):
return self
def __next__(self):
self.a,self.b = self.b,self.a+self.b
if self.a>=self.max:
raise StopIteration
return self.a
fibs = Fibs(1000)
for e in fibs:
print(e)
第一个类是否是第二个的子类
issubclass(class,classinfo)
检查一个实例是否是其对象
isinstance(object,classinfo)
检查对象是否有name属性
hasattr(object,name)
返回属性
getattr(object,name[,defult])
设置属性
setattr(object,name,value)
删除属性
delattr(object,name)
property(fget=None,fset=None,fdel=None,)
fget:获取属性的方法
fset:设置属性的方法
fdel:删除属性的方法
class C:
def __init__(self,size=10):
self.size_v = size
def getsize(self):
return self.size_v
def setsize(self,size):
self.size_v = size
def delsize(self):
del self.size_v
size = property(getsize,setsize,delsize)
c = C()
print(hasattr(c,"size_v")) #True
print(hasattr(c,"size")) #True
print(c.getsize()) #10
c.size = 20
print(c.size) #20
del c.size
print(hasattr(c,"size_v")) #False
print(hasattr(c,"size")) #False
魔法方法
构造
__init__()
__new__(class[,...]) 返回类型
__del__(self) 当被垃圾回收时调用
算数
__add__(self,other) 定义加法行为+
__sub__(self,other) 定义减法行为-
__mul__(self,other) 定义乘法行为*
__truediv__(self,other) 定义真除法行为/
__floordiv__(self,other) 定义整除法//
__mod__(self,other) 取模%
__divmod__(self,other) 当被divmod()调用时的行为 返回地板除之后的余数
__pow__(self,other) 当被power()调用或**运算时的行为
__lshift__(selfother) 定义按位左移位的行为<<
__rshift__(self,other) 定义按位右移位的行为>>
__and__(self,other) 定义按位与操作的行为&
__xor__(self,other) 定义按位异或操作的行为^
__or__(self,other) 定义按位或操作的行为|
一元操作符
__neg__(self) 定义正号的行为
__pos__(self) 定义负号的行为
__abs__(self) 定义当被abs()调用的行为
__invert__(self) 定义按位求反的行为
类型转换
字符转换
__repr__ obj直接输出
__str__ 字符串输入print(obj)
描述符
__get__(self,instance,owner) 用于访问属性,它返回属性的值
__set__(self,instance,value) 将在属性分配操作中调用,不返回任何内容
__delete__(self,instance) 控制删除操作,不返回任何内容
self: 描述符自身实例
instance: 描述符的拥有者实例
owner: 描述符的拥有者本身类
不可变容器定义:
__len__() 定义当被len()调用时的行为
__getitem__() 定义获取容器中指定元素的行为self[key]
可变容器定义:
__len__() 定义当被len()调用时的行为
__getitem__() 定义获取容器中指定元素的行为self[key]
__setitem__() 定义设置容器中指定元素的行为self[key] = value
__delitem__() 定义删除容器中指定元素的行为del self[key]
@classmethod
调用的时候用类名,而不是某个对象
@property
像访问属性一样调用方法
例:=============================================
class Upp(str):
def __new__(clacc,string):
string = string.upper()
return super().__new__(clacc,string)
a = Upp("i love fishc")
print(a) #I LOVE FISHC
例:=============================================
import time as t
class Timer:
def __init__(self):
self.start_time = 0
self.stop_time = 0
self.js = 0
def start(self):
self.start_time = t.time()
print("开始计时")
def stop(self):
self.stop_time = t.time()
if self.start_time == 0:
print("请先开始计时吧")
else:
self._cal()
print("计时结束")
def _cal(self):
self.js = self.stop_time - self.start_time
self.start_time = 0
self.stop_time = 0
def __str__(self):
return str(self.js)
__repr__ = __str__
t1 = Timer()
t1.start()
t.sleep(3)
t1.stop()
print(t1)
例:=============================================
class Celsius:
def __init__(self,value = 20.0):
self.value = float(value)
def __get__(self,instance,owner):
return self.value
def __set__(self,instance,value):
self.value = float(value)
class Fahrenheit:
def __get__(self,instance,owner):
return instance.cel * 1.8 + 32
def __set__(self,instance,value):
instance.cel = (float(value)-32)/1.8
class Temperature:
cel = Celsius()
fah = Fahrenheit()
t = Temperature()
t.cel = 32
print(t.fah) #89.6
print(t.cel) #32.0
t.fah = 60
print(t.cel) #15.555555555555555
例:=============================================
class CountList:
def __init__(self,*args):
self.value = [x for x in args]
self.count = {}.fromkeys(range(len(self.value)),0)
def __len__(self):
return len(self.value)
def __getitem__(self,key):
self.count[key] += 1
return self.value[key]
c1 = CountList(1,3,5,7,9)
c2 = CountList(2,4,6,8,10)
print(c1[1])
print(c1.count)
fibs = Fibs(1000)
for e in fibs:
print(e)
例:=============================================
def fib():
a = 0
b = 1
while True:
a,b = b,a+b
yield a
for each in fib():
if each > 100:
break
print(each,end=' ')
列表推导式
a = [i for i in range(100) if not(i%2) and i%3]
字典推导式
b = {i:i%2==0 for i in range(10)}
集合推导式
c = {i for i in [1,1,2,2,3,4,5,5,6]}
d = (i for i in range(10))
for i in d:
print(i)
# for i in range(2):
# f = open("zzz_"+str(i)+".txt","w+")
# f.write("zzz_value="+str(i))
# f.close()
例:=============================================
import os
import os.path
import shutil
# os.makedirs("test100s")
# print(os.getcwd()+"\\test100s")
# os.makedirs("zzz100s")
# os.makedirs("abcs")
for files in os.listdir(os.getcwd()):
file_path = os.path.join(os.getcwd(),files)
if os.path.isfile(file_path):
if os.path.basename(file_path).startswith("zzz_"):
shutil.move(file_path,file_path.replace("zzz_","zzz100s\\zzz100_"))
print(os.path.basename(file_path))
if os.path.basename(file_path).startswith("abc_"):
shutil.move(file_path,file_path.replace("abc_","abcs\\abc_"))
print(os.path.basename(file_path))
if os.path.basename(file_path).startswith("test_"):
shutil.move(file_path,file_path.replace("test_","test100s\\test100_"))
print(os.path.basename(file_path))
例:=============================================
#获取农历==================================================================
from urllib import request
import json
url = "https://www.sojson.com/open/api/lunar/json.shtml"
result_data = json.loads(request.urlopen(request.Request(url)).read())
print("%s%s月%s " % (result_data["data"]["cnyear"],result_data["data"]["cnmonth"],result_data["data"]["cnday"]))
#查五天t天气==================================================================
from urllib import request
from urllib import parse
import json
url = "武汉"
result_data = request.urlopen(request.Request("https://www.sojson.com/open/api/weather/json.shtml?city="+parse.quote(url))).read()
result_data = result_data.decode("utf-8")
result_data = json.loads(result_data)
for ea in result_data["data"]["forecast"]:
print ("日期:%s\t\t高温:%s\t\t低温:%s\t\t天气:%s" % (ea["date"],ea["high"][2:],ea["low"][2:],ea["type"]))