Python 100 例
作者 | 振哥
來源 | Python與算法社區(qū)
大家好,我是振哥。這是我總結(jié)的 Python 100 個(gè)樣例,原創(chuàng)作品,請(qǐng)大家多多關(guān)照。
以下所有代碼全都至少運(yùn)行一遍,確保可復(fù)現(xiàn)、易于理解、逐步完成入門到進(jìn)階的學(xué)習(xí)。
此教程經(jīng)過我反復(fù)打磨多遍,經(jīng)常為此熬夜,真心不易,文章比較長(zhǎng),看完有用,幫我點(diǎn)個(gè)在看或分享支持。
教程包括 62 個(gè)基礎(chǔ)樣例,12 個(gè)核心樣例,26 個(gè)習(xí)慣用法。如果覺得還不錯(cuò),歡迎轉(zhuǎn)發(fā)、留言或在看。
一、 ?Python 基礎(chǔ) 62 例
1 ?十轉(zhuǎn)二
將十進(jìn)制轉(zhuǎn)換為二進(jìn)制:
>>>?bin(10)
'0b1010'
2 十轉(zhuǎn)八
十進(jìn)制轉(zhuǎn)換為八進(jìn)制:
>>>?oct(9)
'0o11'
3 十轉(zhuǎn)十六
十進(jìn)制轉(zhuǎn)換為十六進(jìn)制:
>>>?hex(15)
'0xf'
4 ?字符串轉(zhuǎn)字節(jié)
字符串轉(zhuǎn)換為字節(jié)類型
>>>?s?=?"apple"
>>>?bytes(s,encoding='utf-8')
b'apple'
5 轉(zhuǎn)為字符串
字符類型、數(shù)值型等轉(zhuǎn)換為字符串類型
>>>?i?=?100
>>>?str(i)
'100'
6 十轉(zhuǎn)ASCII
十進(jìn)制整數(shù)對(duì)應(yīng)的 ASCII 字符
>>>?chr(65)
'A'
7 ASCII轉(zhuǎn)十
ASCII字符對(duì)應(yīng)的十進(jìn)制數(shù)
>>>?ord('A')
65
8 轉(zhuǎn)為字典
創(chuàng)建數(shù)據(jù)字典的幾種方法
>>>?dict()
{}
>>>?dict(a='a',b='b')
{'a':?'a',?'b':?'b'}
>>>?dict(zip(['a','b'],[1,2]))
{'a':?1,?'b':?2}
>>>?dict([('a',1),('b',2)])
{'a':?1,?'b':?2}
9 轉(zhuǎn)為浮點(diǎn)類型
整數(shù)或數(shù)值型字符串轉(zhuǎn)換為浮點(diǎn)數(shù)
>>>?float(3)
3.0
如果不能轉(zhuǎn)化為浮點(diǎn)數(shù),則會(huì)報(bào)ValueError:
>>>?float('a')
Traceback?(most?recent?call?last):
??File?"" ,?line?1,?in?
????float('a')
ValueError:?could?not?convert?string?to?float:?'a'
10 ?轉(zhuǎn)為整型
int(x, base =10)
x 可能為字符串或數(shù)值,將 x 轉(zhuǎn)換為整數(shù)。
如果參數(shù)是字符串,那么它可能包含符號(hào)和小數(shù)點(diǎn)。如果超出普通整數(shù)的表示范圍,一個(gè)長(zhǎng)整數(shù)被返回。
>>>?int('12',16)
18
11 ?轉(zhuǎn)為集合
返回一個(gè) set 對(duì)象,集合內(nèi)不允許有重復(fù)元素:
>>>?a?=?[1,4,2,3,1]
>>>?set(a)
{1,?2,?3,?4}
12 轉(zhuǎn)為切片
class slice(start, stop[, step])
返回一個(gè)由 range(start, stop, step) 指定索引集的 slice 對(duì)象,代碼可讀性變好。
>>>?a?=?[1,4,2,3,1]
>>>?my_slice?=?slice(0,5,2)
>>>?a[my_slice]
[1,?2,?1]
13 轉(zhuǎn)元組
tuple() 將對(duì)象轉(zhuǎn)為一個(gè)不可變的序列類型
>>>?a=[1,3,5]
>>>?a.append(7)
>>>?a
[1,?3,?5,?7]
#禁止a增刪元素,只需轉(zhuǎn)為元組
>>>?t=tuple(a)
>>>?t
(1,?3,?5,?7)
14 轉(zhuǎn)凍結(jié)集合
創(chuàng)建不可修改的集合:
>>>?a?=?frozenset([1,1,3,2,3])
>>>?a?#?a?無?pop,append,insert等方法
frozenset({1,?2,?3})
15 商和余數(shù)
分別取商和余數(shù)
>>>?divmod(10,3)
(3,?1)
16 冪和余同時(shí)做
pow 三個(gè)參數(shù)都給出表示先冪運(yùn)算再取余:
>>>?pow(3,?2,?4)
1
17 四舍五入
四舍五入,ndigits代表小數(shù)點(diǎn)后保留幾位:
>>>?round(10.045,?2)
10.04
>>>?round(10.046,?2)
10.05
18 查看變量所占字節(jié)數(shù)
>>>?import?sys
>>>?a?=?{'a':1,'b':2.0}
>>>?sys.getsizeof(a)?#?變量占用字節(jié)數(shù)
240
19 門牌號(hào)
返回對(duì)象的內(nèi)存地址
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
??????????
>>>?xiaoming?=?Student('001','xiaoming')?
>>>?id(xiaoming)
2281930739080
20 排序函數(shù)
排序:
>>>?a?=?[1,4,2,3,1]
#降序
>>>?sorted(a,reverse=True)
[4,?3,?2,?1,?1]
>>>?a?=?[{'name':'xiaoming','age':18,'gender':'male'},
???????{'name':'xiaohong','age':20,'gender':'female'}]
#按?age升序
>>>?sorted(a,key=lambda?x:?x['age'],reverse=False)
[{'name':?'xiaoming',?'age':?18,?'gender':?'male'},?
{'name':?'xiaohong',?'age':?20,?'gender':?'female'}]
21 求和函數(shù)
求和:
>>>?a?=?[1,4,2,3,1]
>>>?sum(a)
11
#求和初始值為1
>>>?sum(a,1)
12
22 計(jì)算表達(dá)式
計(jì)算字符串型表達(dá)式的值
>>>?s?=?"1?+?3?+5"
>>>?eval(s)
9
>>>?eval('[1,3,5]*3')
[1,?3,?5,?1,?3,?5,?1,?3,?5]
23 真假
>>>?bool(0)
False
>>>?bool(False)
False
>>>?bool(None)
False
>>>?bool([])
False
>>>?bool([False])
True
>>>?bool([0,0,0])
True
24 都為真
如果可迭代對(duì)象的所有元素都為真,那么返回 True,否則返回False
#有0,所以不是所有元素都為真
>>>?all([1,0,3,6])
False
#所有元素都為真
>>>?all([1,2,3])
True
25 至少一個(gè)為真
接受一個(gè)可迭代對(duì)象,如果可迭代對(duì)象里至少有一個(gè)元素為真,那么返回True,否則返回False
#?沒有一個(gè)元素為真
>>>?any([0,0,0,[]])
False
#?至少一個(gè)元素為真
>>>?any([0,0,1])
True
26 獲取用戶輸入
獲取用戶輸入內(nèi)容
>>>?input()
I'm?typing?
"I'm?typing?"
27 print 用法
>>>?lst?=?[1,3,5]
#?f?打印
>>>?print(f'lst:?{lst}')
lst:?[1,?3,?5]
#?format?打印
>>>?print('lst:{}'.format(lst))
lst:[1,?3,?5]
28 字符串格式化
格式化字符串常見用法
>>>?print("i?am?{0},age?{1}".format("tom",18))
i?am?tom,age?18
>>>?print("{:.2f}".format(3.1415926))?#?保留小數(shù)點(diǎn)后兩位
3.14
>>>?print("{:+.2f}".format(-1))?#?帶符號(hào)保留小數(shù)點(diǎn)后兩位
-1.00
>>>?print("{:.0f}".format(2.718))?#?不帶小數(shù)位
3
>>>?print("{:0>3d}".format(5))?#?整數(shù)補(bǔ)零,填充左邊,?寬度為3
005
>>>?print("{:,}".format(10241024))?#?以逗號(hào)分隔的數(shù)字格式
10,241,024
>>>?print("{:.2%}".format(0.718))?#?百分比格式
71.80%
>>>?print("{:.2e}".format(10241024))?#?指數(shù)記法
1.02e+07
29 返回對(duì)象哈希值
返回對(duì)象的哈希值。值得注意,自定義的實(shí)例都可哈希:
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
????????
>>>?xiaoming?=?Student('001','xiaoming')
>>>?hash(xiaoming)
-9223371894234104688
list, dict, set等可變對(duì)象都不可哈希(unhashable):
>>>?hash([1,3,5])
Traceback?(most?recent?call?last):
??File?"" ,?line?1,?in?
????hash([1,3,5])
TypeError:?unhashable?type:?'list'
30 打開文件
返回文件對(duì)象
>>>?import?os
>>>?os.chdir('D:/source/dataset')
>>>?os.listdir()
['drinksbycountry.csv',?'IMDB-Movie-Data.csv',?'movietweetings',?
'titanic_eda_data.csv',?'titanic_train_data.csv']
>>>?o?=?open('drinksbycountry.csv',mode='r',encoding='utf-8')
>>>?o.read()
"country,beer_servings,spirit_servings,wine_servings,total_litres_of_pur
e_alcohol,continent\nAfghanistan,0,0,0,0.0,Asia\nAlbania,89,132,54,4.9,"
mode 取值表:
| 字符 | 意義 |
|---|---|
'r' | 讀?。J(rèn)) |
'w' | 寫入,并先截?cái)辔募?/td> |
'x' | 排它性創(chuàng)建,如果文件已存在則失敗 |
'a' | 寫入,如果文件存在則在末尾追加 |
'b' | 二進(jìn)制模式 |
't' | 文本模式(默認(rèn)) |
'+' | 打開用于更新(讀取與寫入) |
31 查看對(duì)象類型
class type(name, bases, dict)
傳入?yún)?shù),返回 object 類型:
>>>?type({4,6,1})
<class?'set'>
>>>?type({'a':[1,2,3],'b':[4,5,6]})
<class?'dict'>
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
>>>?type(Student('1','xiaoming'))
<class?'__main__.Student'>
32 ?兩種創(chuàng)建屬性方法
返回 property 屬性,典型的用法:
>>>?class?C:
????def?__init__(self):
??????self._x?=?None
????def?getx(self):
??????return?self._x
????def?setx(self,?value):
??????self._x?=?value
????def?delx(self):
??????del?self._x
????#?使用property類創(chuàng)建?property?屬性
????x?=?property(getx,?setx,?delx,?"I'm?the?'x'?property.")
使用 C 類:
>>>?C().x=1
>>>?c=C()
#?屬性x賦值
>>>?c.x=1
#?拿值
>>>?c.getx()
1
#?刪除屬性x
>>>?c.delx()
#?再拿報(bào)錯(cuò)
>>>?c.getx()
Traceback?(most?recent?call?last):
??File?"" ,?line?1,?in?
????c.getx()
??File?"" ,?line?5,?in?getx
????return?self._x
AttributeError:?'C'?object?has?no?attribute?'_x'
#?再屬性賦值
>>>?c.x=1
>>>?c.setx(1)
>>>?c.getx()
1
使用@property裝飾器,實(shí)現(xiàn)與上完全一樣的效果:
class?C:
????def?__init__(self):
????????self._x?=?None
????@property
????def?x(self):
????????return?self._x
[email protected]
????def?x(self,?value):
????????self._x?=?value
[email protected]
????def?x(self):
????????del?self._x
33 是否可調(diào)用
判斷對(duì)象是否可被調(diào)用,能被調(diào)用的對(duì)象是一個(gè)callable 對(duì)象。
>>>?callable(str)
True
>>>?callable(int)
True
Student 對(duì)象實(shí)例目前不可調(diào)用:
>>>?class?Student():
????????def?__init__(self,id,name):
????????????self.id?=?id
????????????self.name?=?name
>>>?xiaoming?=?Student(id='1',name='xiaoming')
>>>?callable(xiaoming)
False
如果 xiaoming能被調(diào)用 , 需要重寫Student類的__call__方法:
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
此時(shí)調(diào)用 xiaoming():
>>>?xiaoming?=?Student('001','xiaoming')
>>>?xiaoming()
I?can?be?called
my?name?is?xiaoming
34 動(dòng)態(tài)刪除屬性
刪除對(duì)象的屬性
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
>>>?xiaoming?=?Student('001','xiaoming')
>>>?delattr(xiaoming,'id')
>>>?hasattr(xiaoming,'id')
False
35 動(dòng)態(tài)獲取對(duì)象屬性
獲取對(duì)象的屬性
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
???????
>>>?xiaoming?=?Student('001','xiaoming')
>>>?getattr(xiaoming,'name')?#?獲取name的屬性值
'xiaoming'
36 對(duì)象是否有某個(gè)屬性
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
????????
>>>?xiaoming?=?Student('001','xiaoming')????????
>>>?getattr(xiaoming,'name')#?判斷?xiaoming有無?name屬性
'xiaoming'
>>>?hasattr(xiaoming,'name')
True
>>>?hasattr(xiaoming,'address')
False
37 isinstance
判斷object是否為classinfo的實(shí)例,是返回true
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
???????
>>>?xiaoming?=?Student('001','xiaoming')
>>>?isinstance(xiaoming,Student)
True
38 父子關(guān)系鑒定
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
????????
>>>?class?Undergraduate(Student):?
???????pass
????????
#?判斷?Undergraduate?類是否為?Student?的子類?
>>>?issubclass(Undergraduate,Student)
True
第二個(gè)參數(shù)可為元組:
>>>?issubclass(int,(int,float))
True
39 所有對(duì)象之根
object 是所有類的基類
>>>?isinstance(1,object)
True
>>>?isinstance([],object)
True
40 一鍵查看對(duì)象所有方法
不帶參數(shù)時(shí)返回當(dāng)前范圍內(nèi)的變量、方法和定義的類型列表;帶參數(shù)時(shí)返回參數(shù)的屬性,方法列表。
>>>?class?Student():
??????def?__init__(self,id,name):
????????self.id?=?id
????????self.name?=?name
>>>?xiaoming?=?Student('001','xiaoming')
>>>?dir(xiaoming)
['__call__',?'__class__',?'__delattr__',?'__dict__',?'__dir__',?'__doc__',?'__eq__',?'__format__',?'__ge__',?'__getattribute__',?'__gt__',?'__hash__',?'__init__',?'__init_subclass__',?'__le__',?'__lt__',?'__module__',?'__ne__',?'__new__',?'__reduce__',?'__reduce_ex__',?'__repr__',?'__setattr__',?'__sizeof__',?'__str__',?'__subclasshook__',?'__weakref__',?'id',?'name']
41 枚舉對(duì)象
Python 的枚舉對(duì)象
>>>?s?=?["a","b","c"]
>>>?for?i,v?in?enumerate(s):
???????print(i,v)
0?a
1?b
2?c
42 創(chuàng)建迭代器
>>>?class?TestIter():
?def?__init__(self,lst):
??self.lst?=?lst
??
?#?重寫可迭代協(xié)議__iter__
?def?__iter__(self):
??print('__iter__?is?called')
??return?iter(self.lst)
迭代 TestIter 類:
>>>?t?=?TestIter()
>>>?t?=?TestIter([1,3,5,7,9])
>>>?for?e?in?t:
?print(e)
?
__iter__?is?called
1
3
5
7
9
43 創(chuàng)建range迭代器
- range(stop)
- range(start, stop[,step])
生成一個(gè)不可變序列的迭代器:
>>>?t?=?range(11)
>>>?t?=?range(0,11,2)
>>>?for?e?in?t:
?????print(e)
0
2
4
6
8
10
44 反向
>>>?rev?=?reversed([1,4,2,3,1])
>>>?for?i?in?rev:
?print(i)
?
1
3
2
4
1
45 打包
聚合各個(gè)可迭代對(duì)象的迭代器:
>>>?x?=?[3,2,1]
>>>?y?=?[4,5,6]
>>>?list(zip(y,x))
[(4,?3),?(5,?2),?(6,?1)]
>>>?for?i,j?in?zip(y,x):
?print(i,j)
4?3
5?2
6?1
46 過濾器
函數(shù)通過 lambda 表達(dá)式設(shè)定過濾條件,保留 lambda 表達(dá)式為True的元素:
>>>?fil?=?filter(lambda?x:?x>10,[1,11,2,45,7,6,13])
>>>?for?e?in?fil:
???????print(e)
11
45
13
47 鏈?zhǔn)奖容^
>>>?i?=?3
>>>?1?3
False
>>>?1?3
True
48 ?鏈?zhǔn)讲僮?/span>
>>>?from?operator?import?(add,?sub)
>>>?def?add_or_sub(a,?b,?oper):
?return?(add?if?oper?==?'+'?else?sub)(a,?b)
>>>?add_or_sub(1,?2,?'-')
-1
49 split 分割**
>>>?'i?love?python'.split('?')
['i',?'love',?'python']
50 replace 替換
>>>?'i\tlove\tpython'.replace('\t',',')
'i,love,python'
51 反轉(zhuǎn)字符串
>>>?st="python"
>>>?''.join(reversed(st))
'nohtyp'

52 使用time模塊打印當(dāng)前時(shí)間
#?導(dǎo)入time模塊
>>>?import?time
#?打印當(dāng)前時(shí)間,返回浮點(diǎn)數(shù)
>>>?seconds?=?time.time()
>>>?seconds
1588858156.6146255
53 浮點(diǎn)數(shù)轉(zhuǎn)時(shí)間結(jié)構(gòu)體
#?浮點(diǎn)數(shù)轉(zhuǎn)時(shí)間結(jié)構(gòu)體
>>>?local_time?=?time.localtime(seconds)
>>>?local_time
time.struct_time(tm_year=2020,?tm_mon=5,?tm_mday=7,?tm_hour=21,?tm_min=29,?tm_sec=16,?tm_wday=3,?tm_yday=128,?tm_isdst=0)
- tm_year: 年
- tm_mon: 月
- tm_mday: 日
- tm_hour: 小時(shí)
- tm_min:分
- tm_sec: 分
- tm_sec: 秒
- tm_wday: 一周中索引([0,6], 周一的索引:0)
- tm_yday: 一年中索引([1,366])
- tm_isdst: 1 if summer time is in effect, 0 if not, and -1 if unknown
54 時(shí)間結(jié)構(gòu)體轉(zhuǎn)時(shí)間字符串
#?時(shí)間結(jié)構(gòu)體轉(zhuǎn)時(shí)間字符串
>>>?str_time?=?time.asctime(local_time)
>>>?str_time
'Thu?May??7?21:29:16?2020'
55 時(shí)間結(jié)構(gòu)體轉(zhuǎn)指定格式時(shí)間字符串
#?時(shí)間結(jié)構(gòu)體轉(zhuǎn)指定格式的時(shí)間字符串
>>>?format_time?=?time.strftime('%Y.%m.%d?%H:%M:%S',local_time)
>>>?format_time
'2020.05.07?21:29:16'
56 時(shí)間字符串轉(zhuǎn)時(shí)間結(jié)構(gòu)體
#?時(shí)間字符串轉(zhuǎn)時(shí)間結(jié)構(gòu)體
>>>?time.strptime(format_time,'%Y.%m.%d?%H:%M:%S')
time.struct_time(tm_year=2020,?tm_mon=5,?tm_mday=7,?tm_hour=21,?tm_min=29,?tm_sec=16,?tm_wday=3,?tm_yday=128,?tm_isdst=-1)
57 年的日歷圖
>>>?import?calendar
>>>?from?datetime?import?date
>>>?mydate=date.today()
>>>?calendar.calendar(2020)
結(jié)果:
??????????????????????????????????2020
??????January???????????????????February???????????????????March????????
Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su
???????1??2??3??4??5??????????????????????1??2?????????????????????????1
?6??7??8??9?10?11?12???????3??4??5??6??7??8??9???????2??3??4??5??6??7??8
13?14?15?16?17?18?19??????10?11?12?13?14?15?16???????9?10?11?12?13?14?15
20?21?22?23?24?25?26??????17?18?19?20?21?22?23??????16?17?18?19?20?21?22
27?28?29?30?31????????????24?25?26?27?28?29?????????23?24?25?26?27?28?29
????????????????????????????????????????????????????30?31
???????April??????????????????????May???????????????????????June
Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su
???????1??2??3??4??5???????????????????1??2??3???????1??2??3??4??5??6??7
?6??7??8??9?10?11?12???????4??5??6??7??8??9?10???????8??9?10?11?12?13?14
13?14?15?16?17?18?19??????11?12?13?14?15?16?17??????15?16?17?18?19?20?21
20?21?22?23?24?25?26??????18?19?20?21?22?23?24??????22?23?24?25?26?27?28
27?28?29?30???????????????25?26?27?28?29?30?31??????29?30
????????July?????????????????????August??????????????????September
Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su
???????1??2??3??4??5??????????????????????1??2??????????1??2??3??4??5??6
?6??7??8??9?10?11?12???????3??4??5??6??7??8??9???????7??8??9?10?11?12?13
13?14?15?16?17?18?19??????10?11?12?13?14?15?16??????14?15?16?17?18?19?20
20?21?22?23?24?25?26??????17?18?19?20?21?22?23??????21?22?23?24?25?26?27
27?28?29?30?31????????????24?25?26?27?28?29?30??????28?29?30
??????????????????????????31
??????October???????????????????November??????????????????December
Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su??????Mo?Tu?We?Th?Fr?Sa?Su
??????????1??2??3??4?????????????????????????1??????????1??2??3??4??5??6
?5??6??7??8??9?10?11???????2??3??4??5??6??7??8???????7??8??9?10?11?12?13
12?13?14?15?16?17?18???????9?10?11?12?13?14?15??????14?15?16?17?18?19?20
19?20?21?22?23?24?25??????16?17?18?19?20?21?22??????21?22?23?24?25?26?27
26?27?28?29?30?31?????????23?24?25?26?27?28?29??????28?29?30?31
??????????????????????????30
58 月的日歷圖
>>>?import?calendar
>>>?from?datetime?import?date
>>>?mydate?=?date.today()
>>>?calendar.month(mydate.year,?mydate.month)
結(jié)果:
??????May?2020
Mo?Tu?We?Th?Fr?Sa?Su
?????????????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
59 判斷是否為閏年
>>>?import?calendar
>>>?from?datetime?import?date
>>>?mydate?=?date.today()
>>>?is_leap?=?calendar.isleap(mydate.year)
>>>?("{}是閏年"?if?is_leap?else?"{}不是閏年\n").format(mydate.year)
'2020是閏年'
60 with 讀寫文件
讀文件:
>>?import?os
>>>?os.chdir('D:/source/dataset')
>>>?os.listdir()
['drinksbycountry.csv',?'IMDB-Movie-Data.csv',?'movietweetings',?'test.csv',?'titanic_eda_data.csv',?'titanic_train_data.csv',?'train.csv']
#?讀文件
>>>?with?open('drinksbycountry.csv',mode='r',encoding='utf-8')?as?f:
??????o?=?f.read()
??????print(o)
寫文件:
#?寫文件
>>>?with?open('new_file.txt',mode='w',encoding='utf-8')?as?f:
??????w?=?f.write('I?love?python\n?It\'s?so?simple')
??????os.listdir()
?
['drinksbycountry.csv',?'IMDB-Movie-Data.csv',?'movietweetings',?'new_file.txt',?'test.csv',?'titanic_eda_data.csv',?'titanic_train_data.csv',?'train.csv']
>>>?with?open('new_file.txt',mode='r',encoding='utf-8')?as?f:
??????o?=?f.read()
??????print(o)
?
I?love?python
?It's?so?simple
61 提取后綴名
>>>?import?os
>>>?os.path.splitext('D:/source/dataset/new_file.txt')
('D:/source/dataset/new_file',?'.txt')?#[1]:后綴名
62 提取完整文件名
>>>?import?os
>>>?os.path.split('D:/source/dataset/new_file.txt')
('D:/source/dataset',?'new_file.txt')
二、 Python 核心?12 例
63 斐波那契數(shù)列前n項(xiàng)
>>>?def?fibonacci(n):
??????a,?b?=?1,?1
??????for?_?in?range(n):
????????yield?a
????????a,?b?=?b,?a+b?#?注意這種賦值
>>>?for?fib?in?fibonacci(10):
??????print(fib)
?
1
1
2
3
5
8
13
21
34
55
64 list 等分 n 組
>>>?from?math?import?ceil
>>>?def?divide_iter(lst,?n):
??????if?n?<=?0:
????????yield?lst
????????return
??????i,?div?=?0,?ceil(len(lst)?/?n)
??????while?i?????????yield?lst[i?*?div:?(i?+?1)?*?div]
????????i?+=?1
??
>>>?for?group?in?divide_iter([1,2,3,4,5],2):
??????print(group)
?
[1,?2,?3]
[4,?5]
65 yield 解釋
有好幾位同學(xué)問我,生成器到底該怎么理解。
在這里我總結(jié)幾句話,看看是否對(duì)不理解生成器的朋友有幫助。
生成器首先是一個(gè) “特殊的” return ,遇到 yield 立即中斷返回。
但是,又與 return 不同,yield 后下一次執(zhí)行會(huì)進(jìn)入到y(tǒng)ield 的下一句代碼,而不像 return 下一次執(zhí)行還是從函數(shù)體的第一句開始執(zhí)行。
可能還是沒說清,那就用圖解釋一下:
第一次 yield 返回 1

第二次迭代,直接到位置 2 這句代碼:

然后再走 for ,再 yield ,重復(fù)下去,直到for結(jié)束。
以上就是理解 yield 的重點(diǎn)一個(gè)方面。
66 裝飾器
66.1 定義裝飾器
time 模塊大家比較清楚,第一個(gè)導(dǎo)入 wraps 函數(shù)(裝飾器)為確保被裝飾的函數(shù)名稱等屬性不發(fā)生改變用的,這點(diǎn)現(xiàn)在不清楚也問題不大,實(shí)踐一下就知道了。
from?functools?import?wraps
import?time
定義一個(gè)裝飾器:print_info,裝飾器函數(shù)入?yún)⒁鬄楹瘮?shù),返回值要求也為函數(shù)。
如下,入?yún)楹瘮?shù) f, 返回參數(shù) info 也為函數(shù),滿足要求。
def?print_info(f):
????"""
????@para:?f,?入?yún)⒑瘮?shù)名稱
????"""
????@wraps(f)?#?確保函數(shù)f名稱等屬性不發(fā)生改變
????def?info():
????????print('正在調(diào)用函數(shù)名稱為:?%s?'?%?(f.__name__,))
????????t1?=?time.time()
????????f()
????????t2?=?time.time()
????????delta?=?(t2?-?t1)
????????print('%s?函數(shù)執(zhí)行時(shí)長(zhǎng)為:%f?s'?%?(f.__name__,delta))
????return?info
66.2使用裝飾器
使用 print_info 裝飾器,分別修飾 f1, f2 函數(shù)。
軟件工程要求盡量一次定義,多次被復(fù)用。
@print_info
def?f1():
????time.sleep(1.0)
@print_info
def?f2():
????time.sleep(2.0)
66.3 使用裝飾后的函數(shù)
使用 f1, f2 函數(shù):
f1()
f2()
#?輸出信息如下:
#?正在調(diào)用函數(shù)名稱為:f1
#?f1?函數(shù)執(zhí)行時(shí)長(zhǎng)為:1.000000?s
#?正在調(diào)用函數(shù)名稱為:f2
#?f2?函數(shù)執(zhí)行時(shí)長(zhǎng)為:2.000000?s
67 迭代器案例
一個(gè)類如何成為迭代器類型,請(qǐng)看官方PEP說明:

即必須實(shí)現(xiàn)兩個(gè)方法(或者叫兩種協(xié)議):__iter__ , __next__
下面編寫一個(gè)迭代器類:
class?YourRange():
????def?__init__(self,?start,?end):
????????self.value?=?start
????????self.end?=?end
????#?成為迭代器類型的關(guān)鍵協(xié)議
????def?__iter__(self):
????????return?self
????#?當(dāng)前迭代器狀態(tài)(位置)的下一個(gè)位置
????def?__next__(self):
????????if?self.value?>=?self.end:
????????????raise?StopIteration
????????cur?=?self.value
????????self.value?+=?1
????????return?cur
使用這個(gè)迭代器:
yr?=?YourRange(5,?12)
for?e?in?yr:
????print(e)
迭代器實(shí)現(xiàn)__iter__ 協(xié)議,它就能在 for 上迭代,參考官網(wǎng)PEP解釋:

文章最后提個(gè)問題,如果此時(shí)運(yùn)行:
next(yr)
會(huì)輸出 5, 還是報(bào)錯(cuò)?
如果 yr 是 list,for 遍歷后,再 next(iter(yr)) 又會(huì)輸出什么?
如果能分清這些問題,恭喜你,已經(jīng)真正理解迭代器迭代和容器遍歷的區(qū)別。如果你還拿不準(zhǔn),歡迎交流。
下面使用 4 種常見的繪圖庫繪制柱狀圖和折線圖,使用盡可能最少的代碼繪制,快速入門這些庫是本文的寫作目的。
68 matplotlib
導(dǎo)入包:
import?matplotlib?
matplotlib.__version__??#?'2.2.2'
import?matplotlib.pyplot?as?plt
繪圖代碼:
import?matplotlib.pyplot?as?plt?
plt.plot([0,?1,?2,?3,?4,?5],
????????[1.5,?1,?-1.3,?0.7,?0.8,?0.9]
????????,c='red')
plt.bar([0,?1,?2,?3,?4,?5],
????????[2,?0.5,?0.7,?-1.2,?0.3,?0.4]
????????)
plt.show()

69 seaborn
導(dǎo)入包:
import?seaborn?as?sns?
sns.__version__?#?'0.8.0'
繪制圖:
sns.barplot([0,?1,?2,?3,?4,?5],
????????[1.5,?1,?-1.3,?0.7,?0.8,?0.9]
????????)
sns.pointplot([0,?1,?2,?3,?4,?5],
????????[2,?0.5,?0.7,?-1.2,?0.3,?0.4]
????????)
plt.show()

70 plotly 繪圖
導(dǎo)入包:
import?plotly?
plotly.__version__?#?'2.0.11'
繪制圖(自動(dòng)打開html):
import?plotly.graph_objs?as?go
import?plotly.offline?as?offline
pyplt?=?offline.plot
sca?=?go.Scatter(x=[0,?1,?2,?3,?4,?5],
?????????????y=[1.5,?1,?-1.3,?0.7,?0.8,?0.9]
????????????)
bar?=?go.Bar(x=[0,?1,?2,?3,?4,?5],
????????????y=[2,?0.5,?0.7,?-1.2,?0.3,?0.4]
????????????)
fig?=?go.Figure(data?=?[sca,bar])
pyplt(fig)

71 pyecharts
導(dǎo)入包:
import?pyecharts
pyecharts.__version__?#?'1.7.1'
繪制圖(自動(dòng)打開html):
bar?=?(
????????Bar()
????????.add_xaxis([0,?1,?2,?3,?4,?5])
????????.add_yaxis('ybar',[1.5,?1,?-1.3,?0.7,?0.8,?0.9])
????)
line?=?(Line()
????????.add_xaxis([0,?1,?2,?3,?4,?5])
????????.add_yaxis('yline',[2,?0.5,?0.7,?-1.2,?0.3,?0.4])
????????)
bar.overlap(line)
bar.render_notebook()

大家在復(fù)現(xiàn)代碼時(shí),需要注意API與包的版本緊密相關(guān),與上面版本不同的包其內(nèi)的API可能與以上寫法有略有差異,大家根據(jù)情況自行調(diào)整即可。
matplotlib 繪制三維 3D 圖形的方法,主要鎖定在繪制 3D 曲面圖和等高線圖。
72 理解 meshgrid
要想掌握 3D 曲面圖,需要首先理解 meshgrid 函數(shù)。
導(dǎo)入包:
import?numpy?as?np
import?matplotlib.pyplot?as?plt
創(chuàng)建一維數(shù)組 x
nx,?ny?=?(5,?3)
x?=?np.linspace(0,?1,?nx)
x
#?結(jié)果
#?array([0.??,?0.25,?0.5?,?0.75,?1.??])
創(chuàng)建一維數(shù)組 y
y?=?np.linspace(0,?1,?ny)
y?
#?結(jié)果
#?array([0.?,?0.5,?1.?])
使用 meshgrid 生成網(wǎng)格點(diǎn):
xv,?yv?=?np.meshgrid(x,?y)
xv
xv 結(jié)果:
array([[0.??,?0.25,?0.5?,?0.75,?1.??],
???????[0.??,?0.25,?0.5?,?0.75,?1.??],
???????[0.??,?0.25,?0.5?,?0.75,?1.??]])
yv 結(jié)果:
array([[0.?,?0.?,?0.?,?0.?,?0.?],
???????[0.5,?0.5,?0.5,?0.5,?0.5],
???????[1.?,?1.?,?1.?,?1.?,?1.?]])
繪制網(wǎng)格點(diǎn):
plt.scatter(xv.flatten(),yv.flatten(),c='red')
plt.xticks(ticks=x)
plt.yticks(ticks=y)

以上就是 meshgrid 功能:創(chuàng)建網(wǎng)格點(diǎn),它是繪制 3D 曲面圖的必用方法之一。
73 繪制曲面圖
導(dǎo)入 3D 繪圖模塊:
from?mpl_toolkits.mplot3d?import?Axes3D
生成X,Y,Z
#?X,?Y?
x?=?np.arange(-5,?5,?0.25)
y?=?np.arange(-5,?5,?0.25)
X,?Y?=?np.meshgrid(x,?y)????#?x-y?平面的網(wǎng)格
R?=?np.sqrt(X?**?2?+?Y?**?2)
#?Z
Z?=?np.sin(R)
繪制 3D 曲面圖:
fig?=?plt.figure()
ax?=?Axes3D(fig)
plt.xticks(ticks=np.arange(-5,6))
plt.yticks(ticks=np.arange(-5,6))
ax.plot_surface(X,?Y,?Z,?cmap=plt.get_cmap('rainbow'))
plt.show()

74 等高線圖
以上 3D 曲面圖的在 xy平面、 xz平面、yz平面投影,即是等高線圖。
xy 平面投影得到的等高線圖:
fig?=?plt.figure()
ax?=?Axes3D(fig)
plt.xticks(ticks=np.arange(-5,6))
plt.yticks(ticks=np.arange(-5,6))
ax.contourf(X,?Y,?Z,?zdir='z',?offset=-1,?cmap=plt.get_cmap('rainbow'))
plt.show()

三、 Python 習(xí)慣 26 例
75 / 返回浮點(diǎn)數(shù)
即便兩個(gè)整數(shù),/ 操作也會(huì)返回浮點(diǎn)數(shù)
In?[1]:?8/5
Out[1]:?1.6
76 // 得到整數(shù)部分
使用 //快速得到兩數(shù)相除的整數(shù)部分,并且返回整型,此操作符容易忽略,但確實(shí)很實(shí)用。
In?[2]:?8//5
Out[2]:?1
In?[3]:?a?=?8//5
In?[4]:?type(a)
Out[4]:?int
77 % 得到余數(shù)
%得到兩數(shù)相除的余數(shù):
In?[6]:?8%5
Out[6]:?3
78 ** 計(jì)算乘方
** 計(jì)算幾次方
In?[7]:?2**3
Out[7]:?8
79 交互模式下的_
在交互模式下,上一次打印出來的表達(dá)式被賦值給變量 _
In?[8]:?2*3.02+1
Out[8]:?7.04
In?[9]:?1+_
Out[9]:?8.04
80 單引號(hào)和雙引號(hào)微妙不同
使用單引號(hào)和雙引號(hào)的微妙不同
使用一對(duì)雙引號(hào)時(shí),打印下面串無需轉(zhuǎn)義字符:
In?[10]:?print("That?isn't?a?horse")
That?isn't?a?horse
使用單引號(hào)時(shí),需要添加轉(zhuǎn)義字符 \:
In?[11]:?print('That?isn\'t?a?horse')
That?isn't?a?horse
81 跨行連續(xù)輸入
符串字面值可以跨行連續(xù)輸入;一種方式是用一對(duì)三重引號(hào):""" 或 '''
In?[12]:?print("""You're?just?pounding?two
????...:?coconut?halves?together.""")
You're?just?pounding?two
coconut?halves?together.
82 數(shù)字和字符串
In?[13]:?3*'Py'
Out[13]:?'PyPyPy'
83 連接字面值
堆積起來就行,什么都不用寫:
In?[14]:?'Py''thon'
Out[14]:?'Python'
84 for 和 else
一般語言 else 只能和 if 搭,Python 中卻支持 for 和 else, try 和 else.
for 和 else 搭后,遍歷結(jié)束便會(huì)執(zhí)行 else
In?[29]:?for?i?in?range(3):
????...:?????for?j?in?range(i):
????...:?????????print(j)
????...:?????else:
????...:?????????print('第%d輪遍歷結(jié)束\n'%(i+1,))
????...:
第1輪遍歷結(jié)束
0
第2輪遍歷結(jié)束
0
1
第3輪遍歷結(jié)束
85. if not x
直接使用 x 和 not x 判斷 x 是否為 None 或空
x = [1,3,5]
if x:
print('x is not empty ')
if not x:
print('x is empty')
下面寫法不夠 Pythoner
if x and len(x) > 0:
print('x is not empty ')
if x is None or len(x) == 0:
print('x is empty')
86. enumerate 枚舉
直接使用 enumerate 枚舉容器,第二個(gè)參數(shù)表示索引的起始值
x = [1, 3, 5]
for i, e in enumerate(x, 10): # 枚舉
print(i, e)
下面寫法不夠 Pythoner:
i = 0
while i < len(x):
print(i+10, x[i])
i+=1
87. in
判斷字符串是否包含某個(gè)子串,使用in明顯更加可讀:
x = 'zen_of_python'
if 'zen' in x:
print('zen is in')
find 返回值 要與 -1 判斷,不太符合習(xí)慣:
if x.find('zen') != -1:
print('zen is in')
88 zip 打包
使用 zip 打包后結(jié)合 for 使用輸出一對(duì),更加符合習(xí)慣:
keys = ['a', 'b', 'c']
values = [1, 3, 5]
for k, v in zip(keys, values):
print(k, v)
下面不符合 Python 習(xí)慣:
d = {}
i = 0
for k in keys:
print(k, values[i])
i += 1
89 一對(duì) '''
打印被分為多行的字符串,使用一對(duì) ''' 更加符合 Python 習(xí)慣:
print('''"Oh no!" He exclaimed.
"It's the blemange!"''')
下面寫法就太不 Python 風(fēng)格:
print('"Oh no!" He exclaimed.\n' +
'It\'s the blemange!"')
90 交換元素
直接解包賦值,更加符合 Python 風(fēng)格:
a, b = 1, 3
a, b = b, a # 交換a,b
不要再用臨時(shí)變量 tmp ,這不符合 Python 習(xí)慣:
tmp = a
a = b
b = tmp
91 join 串聯(lián)
串聯(lián)字符串,更習(xí)慣使用 join:
chars = ['P', 'y', 't', 'h', 'o', 'n']
name = ''.join(chars)
print(name)
下面不符合 Python 習(xí)慣:
name = ''
for c in chars:
name += c
print(name)
92 列表生成式
列表生成式構(gòu)建高效,符合 Python 習(xí)慣:
data = [1, 2, 3, 5, 8]
result = [i * 2 for i in data if i & 1] # 奇數(shù)則乘以2
print(result) # [2, 6, 10]
下面寫法不夠 Pythoner:
results = []
for e in data:
if e & 1:
results.append(e*2)
print(results)
93 字典生成式
除了列表生成式,還有字典生成式:
keys = ['a', 'b', 'c']
values = [1, 3, 5]
d = {k: v for k, v in zip(keys, values)}
print(d)
下面寫法不太 Pythoner:
d = {}
for k, v in zip(keys, values):
d[k] = v
print(d)
94 __name__ == '__main__'有啥用
曾幾何時(shí),看這別人代碼這么寫,我們也就跟著這么用吧,其實(shí)還沒有完全弄清楚這行到底干啥。
def mymain():
print('Doing something in module', __name__)
if __name__ == '__main__':
print('Executed from command line')
mymain()
加入上面腳本命名為 MyModule,不管在 vscode 還是 pycharm 直接啟動(dòng),則直接打印出:
Executed from command line
Doing something in module __main__
這并不奇怪,和我們預(yù)想一樣,因?yàn)橛袩o這句 __main__ ,都會(huì)打印出這些。
但是當(dāng)我們 import MyModule 時(shí),如果沒有這句,直接就打印出:
In [2]: import MyModule
Executed from command line
Doing something in module MyModule
只是導(dǎo)入就直接執(zhí)行 mymain 函數(shù),這不符合我們預(yù)期。
如果有主句,導(dǎo)入后符合預(yù)期:
In [6]: import MyModule
In [7]: MyModule.mymain()
Doing something in module MyModule
95 字典默認(rèn)值
In[1]: d = {'a': 1, 'b': 3}
In[2]: d.get('b', []) # 存在鍵 'b'
Out[2]: 3
In[3]: d.get('c', []) # 不存在鍵 'c',返回[]
Out[3]: []
96 lambda 函數(shù)
lambda 函數(shù)使用方便,主要由入?yún)⒑头祷刂到M成,被廣泛使用在 max, map, reduce, filter 等函數(shù)的 key 參數(shù)中。
如下,求 x 中絕對(duì)值最大的元素,key 函數(shù)確定abs(x)作為比較大小的方法:
x = [1, 3, -5]
y = max(x, key=lambda x: abs(x))
print(y) # -5
97 max
求 x 中絕對(duì)值最大的元素,key 函數(shù)確定abs(x)作為比較大小的方法:
x = [1, 3, -5]
y = max(x, key=lambda x: abs(x))
print(y) # -5
98 map
map 函數(shù)映射 fun 到容器中每個(gè)元素,并返回迭代器 x
x = map(str, [1, 3, 5])
for e in x:
print(e, type(e))
下面寫法不夠 Pythoner
for e in [1, 3, 5]:
print(e, str(e)) # '1','3','5'
99 reduce
reduce 是在 functools 中,第一個(gè)參數(shù)是函數(shù),其必須含有 2 個(gè)參數(shù),最后歸約為一個(gè)標(biāo)量。
from functools import reduce
x = [1, 3, 5]
y = reduce(lambda p1, p2: p1*p2, x)
print(y) # 15
下面寫法不夠 Pythoner:
y = 1
for e in x:
y *= e
print(y)
100 filter
使用 filter 找到滿足 key 函數(shù)指定條件的元素,并返回迭代器
如下,使用 filter 找到所有奇數(shù):
x = [1, 2, 3, 5]
odd = filter(lambda e: e % 2, x)
for e in odd: # 找到奇數(shù)
print(e)
還有另外一種方法,使用列表生成式,直接得到一個(gè)odd 容器,
odd = [e for e in x if e % 2]
print(odd) # [1,3,5]
下面寫法最不符合 Python 習(xí)慣:
odd = []
for e in x:
if e % 2:
odd.append(e)
print(odd) # [1,3,5]
此教程反復(fù)打磨多遍,真心不易,如果覺得還不錯(cuò),你能轉(zhuǎn)發(fā)、留言或在看支持一下嗎?
