Python 常用代碼【100 例】

一、 ?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ù)對應(yīng)的 ASCII 字符

>>>?chr(65)

'A'

7 、ASCII轉(zhuǎn)十

ASCII字符對應(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ù),則會報(bào)ValueError:

>>>?float('a')

Traceback?(most?recent?call?last):

File"<pyshell#7>",?line1,in

float('a')

ValueError:?couldnotconvert?string?to?float:'a'

10 、 轉(zhuǎn)為整型

int(x, base =10)

x 可能為字符串或數(shù)值,將 x 轉(zhuǎn)換為整數(shù)。

如果參數(shù)是字符串,那么它可能包含符號和小數(shù)點(diǎn)。如果超出普通整數(shù)的表示范圍,一個長整數(shù)被返回。

>>>?int('12',16)

18

11、? 轉(zhuǎn)為集合

返回一個 set 對象,集合內(nèi)不允許有重復(fù)元素:

>>>?a?=?[1,4,2,3,1]

>>>?set(a)

{1,2,3,4}

12 、轉(zhuǎn)為切片

class?slice(start,?stop[,?step])

返回一個由 range(start, stop, step) 指定索引集的 slice 對象,代碼可讀性變好。

>>>?a?=?[1,4,2,3,1]

>>>?my_slice?=?slice(0,5,2)

>>>?a[my_slice]

[1,2,1]

13 、轉(zhuǎn)元組

tuple()?將對象轉(zhuǎn)為一個不可變的序列類型

>>>?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 、冪和余同時做

pow 三個參數(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ù)

>>>?importsys

>>>?a?=?{'a':1,'b':2.0}

>>>?sys.getsizeof(a)#?變量占用字節(jié)數(shù)

240

19、 門牌號

返回對象的內(nèi)存地址

>>>?classStudent():

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=lambdax:?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 、都為真

如果可迭代對象的所有元素都為真,那么返回?True,否則返回False

#有0,所以不是所有元素都為真

>>>?all([1,0,3,6])

False

#所有元素都為真

>>>?all([1,2,3])

True

25、 至少一個為真

接受一個可迭代對象,如果可迭代對象里至少有一個元素為真,那么返回True,否則返回False

#?沒有一個元素為真

>>>?any([0,0,0,[]])

False

#?至少一個元素為真

>>>?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,age18

>>>?print("{:.2f}".format(3.1415926))#?保留小數(shù)點(diǎn)后兩位

3.14

>>>?print("{:+.2f}".format(-1))#?帶符號保留小數(shù)點(diǎn)后兩位

-1.00

>>>?print("{:.0f}".format(2.718))#?不帶小數(shù)位

3

>>>?print("{:0>3d}".format(5))#?整數(shù)補(bǔ)零,填充左邊,?寬度為3

005

>>>?print("{:,}".format(10241024))#?以逗號分隔的數(shù)字格式

10,241,024

>>>?print("{:.2%}".format(0.718))#?百分比格式

71.80%

>>>?print("{:.2e}".format(10241024))#?指數(shù)記法

1.02e+07

29 、返回對象哈希值

返回對象的哈希值。值得注意,自定義的實(shí)例都可哈希:

>>>?classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

>>>?xiaoming?=?Student('001','xiaoming')

>>>?hash(xiaoming)

-9223371894234104688

list,?dict,?set等可變對象都不可哈希(unhashable):

>>>?hash([1,3,5])

Traceback?(most?recent?call?last):

File"<pyshell#71>",?line1,in

hash([1,3,5])

TypeError:?unhashable?type:'list'

30 、打開文件

返回文件對象

>>>?importos

>>>?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)辔募?/p>

'x'排它性創(chuàng)建,如果文件已存在則失敗

'a'寫入,如果文件存在則在末尾追加

'b'二進(jìn)制模式

't'文本模式(默認(rèn))

'+'打開用于更新(讀取與寫入)

31、 查看對象類型

class?type(name,?bases,?dict)

傳入?yún)?shù),返回?object?類型:

>>>?type({4,6,1})

>>>type({'a':[1,2,3],'b':[4,5,6]})

>>>classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

>>>?type(Student('1','xiaoming'))

32 、 兩種創(chuàng)建屬性方法

返回 property 屬性,典型的用法:

>>>?classC:

def__init__(self):

self._x?=None

defgetx(self):

returnself._x

defsetx(self,?value):

self._x?=?value

defdelx(self):

delself._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)錯

>>>?c.getx()

Traceback?(most?recent?call?last):

File"<pyshell#118>",?line1,in

c.getx()

File"<pyshell#112>",?line5,ingetx

returnself._x

AttributeError:'C'object?has?no?attribute'_x'

#?再屬性賦值

>>>?c.x=1

>>>?c.setx(1)

>>>?c.getx()

1

使用@property裝飾器,實(shí)現(xiàn)與上完全一樣的效果:

classC:

def__init__(self):

self._x?=None

????@property

defx(self):

returnself._x

????@x.setter

defx(self,?value):

self._x?=?value

????@x.deleter

defx(self):

delself._x

33、 是否可調(diào)用

判斷對象是否可被調(diào)用,能被調(diào)用的對象是一個callable?對象。

>>>?callable(str)

True

>>>?callable(int)

True

Student 對象實(shí)例目前不可調(diào)用:

>>>?classStudent():

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__方法:

>>>?classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

此時調(diào)用 xiaoming():

>>>?xiaoming?=?Student('001','xiaoming')

>>>?xiaoming()

I?can?be?called

my?nameisxiaoming

34、 動態(tài)刪除屬性

刪除對象的屬性

>>>?classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

>>>?xiaoming?=?Student('001','xiaoming')

>>>?delattr(xiaoming,'id')

>>>?hasattr(xiaoming,'id')

False

35 、動態(tài)獲取對象屬性

獲取對象的屬性

>>>?classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

>>>?xiaoming?=?Student('001','xiaoming')

>>>?getattr(xiaoming,'name')#?獲取name的屬性值

'xiaoming'

36、 對象是否有某個屬性

>>>?classStudent():

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

>>>?classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

>>>?xiaoming?=?Student('001','xiaoming')

>>>?isinstance(xiaoming,Student)

True

38、 父子關(guān)系鑒定

>>>?classStudent():

def__init__(self,id,name):

self.id?=?id

self.name?=?name

>>>?classUndergraduate(Student):

pass

#?判斷?Undergraduate?類是否為?Student?的子類?

>>>?issubclass(Undergraduate,Student)

True

第二個參數(shù)可為元組:

>>>?issubclass(int,(int,float))

True

39 、所有對象之根

object 是所有類的基類

>>>?isinstance(1,object)

True

>>>?isinstance([],object)

True

40 、一鍵查看對象所有方法

不帶參數(shù)時返回當(dāng)前范圍內(nèi)的變量、方法和定義的類型列表;帶參數(shù)時返回參數(shù)的屬性,方法列表。

>>>?classStudent():

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、 枚舉對象

Python 的枚舉對象

>>>?s?=?["a","b","c"]

>>>?fori,vinenumerate(s):

print(i,v)

0a

1b

2c

42 、創(chuàng)建迭代器

>>>?classTestIter():

def__init__(self,lst):

self.lst?=?lst

#?重寫可迭代協(xié)議__iter__

def__iter__(self):

print('__iter__?is?called')

returniter(self.lst)

迭代 TestIter 類:

>>>?t?=?TestIter()

>>>?t?=?TestIter([1,3,5,7,9])

>>>?foreint:

print(e)

__iter__iscalled

1

3

5

7

9

43 、創(chuàng)建range迭代器

range(stop)

range(start, stop[,step])

生成一個不可變序列的迭代器:

>>>?t?=?range(11)

>>>?t?=?range(0,11,2)

>>>?foreint:

print(e)

0

2

4

6

8

10

44 、反向

>>>?rev?=?reversed([1,4,2,3,1])

>>>?foriinrev:

print(i)

1

3

2

4

1

45、 打包

聚合各個可迭代對象的迭代器:

>>>?x?=?[3,2,1]

>>>?y?=?[4,5,6]

>>>?list(zip(y,x))

[(4,3),?(5,2),?(6,1)]

>>>?fori,jinzip(y,x):

print(i,j)

43

52

61

46、 過濾器

函數(shù)通過 lambda 表達(dá)式設(shè)定過濾條件,保留 lambda 表達(dá)式為True的元素:

>>>?fil?=?filter(lambdax:?x>10,[1,11,2,45,7,6,13])

>>>?foreinfil:

print(e)

11

45

13

47、 鏈?zhǔn)奖容^

>>>?i?=3

>>>?1<?i?<3

False

>>>?1<?i?<=3

True

48? 、鏈?zhǔn)讲僮?/b>

>>>?fromoperatorimport(add,?sub)

>>>?defadd_or_sub(a,?b,?oper):

return(addifoper?=='+'elsesub)(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)前時間

#?導(dǎo)入time模塊

>>>?importtime

#?打印當(dāng)前時間,返回浮點(diǎn)數(shù)

>>>?seconds?=?time.time()

>>>?seconds

1588858156.6146255

53 、浮點(diǎn)數(shù)轉(zhuǎn)時間結(jié)構(gòu)體

#?浮點(diǎn)數(shù)轉(zhuǎn)時間結(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: 小時

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 、時間結(jié)構(gòu)體轉(zhuǎn)時間字符串

#?時間結(jié)構(gòu)體轉(zhuǎn)時間字符串

>>>?str_time?=?time.asctime(local_time)

>>>?str_time

'Thu?May??7?21:29:16?2020'

55 、時間結(jié)構(gòu)體轉(zhuǎn)指定格式時間字符串

#?時間結(jié)構(gòu)體轉(zhuǎn)指定格式的時間字符串

>>>?format_time?=?time.strftime('%Y.%m.%d?%H:%M:%S',local_time)

>>>?format_time

'2020.05.07?21:29:16'

56、 時間字符串轉(zhuǎn)時間結(jié)構(gòu)體

#?時間字符串轉(zhuǎn)時間結(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 、年的日歷圖

>>>?importcalendar

>>>?fromdatetimeimportdate

>>>?mydate=date.today()

>>>?calendar.calendar(2020)

58、 月的日歷圖

>>>?importcalendar

>>>?fromdatetimeimportdate

>>>?mydate?=?date.today()

>>>?calendar.month(mydate.year,?mydate.month)

59 、判斷是否為閏年

>>>?importcalendar

>>>?fromdatetimeimportdate

>>>?mydate?=?date.today()

>>>?is_leap?=?calendar.isleap(mydate.year)

>>>?("{}是閏年"ifis_leapelse"{}不是閏年\n").format(mydate.year)

'2020是閏年'

60、 with 讀寫文件

讀文件:

>>importos

>>>?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']

#?讀文件

>>>?withopen('drinksbycountry.csv',mode='r',encoding='utf-8')asf:

o?=?f.read()

print(o)

寫文件:

#?寫文件

>>>?withopen('new_file.txt',mode='w',encoding='utf-8')asf:

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']

>>>?withopen('new_file.txt',mode='r',encoding='utf-8')asf:

o?=?f.read()

print(o)

I?love?python

It's?so?simple

61、 提取后綴名

>>>?importos

>>>?os.path.splitext('D:/source/dataset/new_file.txt')

('D:/source/dataset/new_file','.txt')#[1]:后綴名

62、 提取完整文件名

>>>?importos

>>>?os.path.split('D:/source/dataset/new_file.txt')

('D:/source/dataset','new_file.txt')

二、 Python 核心?12 例

63 、斐波那契數(shù)列前n項(xiàng)

>>>?deffibonacci(n):

a,?b?=1,1

for_inrange(n):

yielda

a,?b?=?b,?a+b#?注意這種賦值

>>>?forfibinfibonacci(10):

print(fib)

1

1

2

3

5

8

13

21

34

55

64 、list 等分 n 組

>>>?frommathimportceil

>>>?defdivide_iter(lst,?n):

ifn?<=0:

yieldlst

return

i,?div?=0,?ceil(len(lst)?/?n)

whilei?<?n:

yieldlst[i?*?div:?(i?+1)?*?div]

i?+=1

>>>?forgroupindivide_iter([1,2,3,4,5],2):

print(group)

[1,2,3]

[4,5]

65、 yield 解釋

有好幾位同學(xué)問我,生成器到底該怎么理解。

在這里我總結(jié)幾句話,看看是否對不理解生成器的朋友有幫助。

生成器首先是一個 “特殊的” return ,遇到 yield 立即中斷返回。

但是,又與 return 不同,yield 后下一次執(zhí)行會進(jìn)入到y(tǒng)ield 的下一句代碼,而不像 return 下一次執(zhí)行還是從函數(shù)體的第一句開始執(zhí)行。

可能還是沒說清,那就用圖解釋一下:

第一次 yield 返回 1

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

然后再走 for ,再 yield ,重復(fù)下去,直到for結(jié)束。

以上就是理解 yield 的重點(diǎn)一個方面。

66、 裝飾器

66.1 定義裝飾器

time 模塊大家比較清楚,第一個導(dǎo)入?wraps?函數(shù)(裝飾器)為確保被裝飾的函數(shù)名稱等屬性不發(fā)生改變用的,這點(diǎn)現(xiàn)在不清楚也問題不大,實(shí)踐一下就知道了。

fromfunctoolsimportwraps

importtime

定義一個裝飾器:print_info,裝飾器函數(shù)入?yún)⒁鬄楹瘮?shù),返回值要求也為函數(shù)。

如下,入?yún)楹瘮?shù) f, 返回參數(shù) info 也為函數(shù),滿足要求。

defprint_info(f):

"""

@para:?f,?入?yún)⒑瘮?shù)名稱

"""

????@wraps(f)?#?確保函數(shù)f名稱等屬性不發(fā)生改變

definfo():

print('正在調(diào)用函數(shù)名稱為:?%s?'%?(f.__name__,))

t1?=?time.time()

f()

t2?=?time.time()

delta?=?(t2?-?t1)

print('%s?函數(shù)執(zhí)行時長為:%f?s'%?(f.__name__,delta))

returninfo

66.2使用裝飾器

使用 print_info 裝飾器,分別修飾 f1, f2 函數(shù)。

軟件工程要求盡量一次定義,多次被復(fù)用。

@print_info

deff1():

time.sleep(1.0)

@print_info

deff2():

time.sleep(2.0)

66.3 使用裝飾后的函數(shù)

使用 f1, f2 函數(shù):

f1()

f2()

#?輸出信息如下:

#?正在調(diào)用函數(shù)名稱為:f1

#?f1?函數(shù)執(zhí)行時長為:1.000000?s

#?正在調(diào)用函數(shù)名稱為:f2

#?f2?函數(shù)執(zhí)行時長為:2.000000?s

67 、迭代器案例

一個類如何成為迭代器類型,請看官方PEP說明:

PEP說明

即必須實(shí)現(xiàn)兩個方法(或者叫兩種協(xié)議):__iter__?,?__next__

下面編寫一個迭代器類:

classYourRange():

def__init__(self,?start,?end):

self.value?=?start

self.end?=?end

#?成為迭代器類型的關(guān)鍵協(xié)議

def__iter__(self):

returnself

#?當(dāng)前迭代器狀態(tài)(位置)的下一個位置

def__next__(self):

ifself.value?>=?self.end:

raiseStopIteration

cur?=?self.value

self.value?+=1

returncur

使用這個迭代器:

yr?=?YourRange(5,12)

foreinyr:

print(e)

迭代器實(shí)現(xiàn)__iter__?協(xié)議,它就能在 for 上迭代,參考官網(wǎng)PEP解釋:

文章最后提個問題,如果此時運(yùn)行:

next(yr)

會輸出 5, 還是報(bào)錯?

如果 yr 是 list,for 遍歷后,再 next(iter(yr)) 又會輸出什么?

如果能分清這些問題,恭喜你,已經(jīng)真正理解迭代器迭代和容器遍歷的區(qū)別。如果你還拿不準(zhǔn),歡迎交流。

下面使用 4 種常見的繪圖庫繪制柱狀圖和折線圖,使用盡可能最少的代碼繪制,快速入門這些庫是本文的寫作目的。

68、 matplotlib

導(dǎo)入包:

importmatplotlib

matplotlib.__version__#?'2.2.2'

importmatplotlib.pyplotasplt

繪圖代碼:

importmatplotlib.pyplotasplt

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)入包:

importseabornassns

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)入包:

importplotly

plotly.__version__#?'2.0.11'

繪制圖(自動打開html):

importplotly.graph_objsasgo

importplotly.offlineasoffline

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)入包:

importpyecharts

pyecharts.__version__#?'1.7.1'

繪制圖(自動打開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)代碼時,需要注意API與包的版本緊密相關(guān),與上面版本不同的包其內(nèi)的API可能與以上寫法有略有差異,大家根據(jù)情況自行調(diào)整即可。

matplotlib 繪制三維 3D 圖形的方法,主要鎖定在繪制 3D 曲面圖和等高線圖。

72、 理解 meshgrid

要想掌握 3D 曲面圖,需要首先理解 meshgrid 函數(shù)。

導(dǎo)入包:

importnumpyasnp

importmatplotlib.pyplotasplt

創(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 繪圖模塊:

frommpl_toolkits.mplot3dimportAxes3D

生成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ù)

即便兩個整數(shù),/?操作也會返回浮點(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 、單引號和雙引號微妙不同

使用單引號和雙引號的微妙不同

使用一對雙引號時,打印下面串無需轉(zhuǎn)義字符:

In?[10]:?print("That?isn't?a?horse")

That?isn't?a?horse

使用單引號時,需要添加轉(zhuǎn)義字符?\:

In?[11]:?print('That?isn\'t?a?horse')

That?isn't?a?horse

81 、跨行連續(xù)輸入

符串字面值可以跨行連續(xù)輸入;一種方式是用一對三重引號:"""?或?'''

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é)束便會執(zhí)行 else

In?[29]:foriinrange(3):

...:forjinrange(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 枚舉容器,第二個參數(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

判斷字符串是否包含某個子串,使用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 使用輸出一對,更加符合習(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 、一對 '''

打印被分為多行的字符串,使用一對?'''?更加符合 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

不要再用臨時變量 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í)還沒有完全弄清楚這行到底干啥。

def mymain():

print('Doing something in module', __name__)

if __name__ == '__main__':

print('Executed from command line')

mymain()

加入上面腳本命名為 MyModule,不管在 vscode 還是 pycharm 直接啟動,則直接打印出:

Executed from command line

Doing something in module __main__

這并不奇怪,和我們預(yù)想一樣,因?yàn)橛袩o這句?__main__?,都會打印出這些。

但是當(dāng)我們?import MyModule?時,如果沒有這句,直接就打印出:

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 中絕對值最大的元素,key 函數(shù)確定abs(x)作為比較大小的方法:

x = [1, 3, -5]

y = max(x, key=lambda x: abs(x))

print(y) # -5

97 、max

求 x 中絕對值最大的元素,key 函數(shù)確定abs(x)作為比較大小的方法:

x = [1, 3, -5]

y = max(x, key=lambda x: abs(x))

print(y) # -5

98、 map

map 函數(shù)映射 fun 到容器中每個元素,并返回迭代器 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 中,第一個參數(shù)是函數(shù),其必須含有 2 個參數(shù),最后歸約為一個標(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)

還有另外一種方法,使用列表生成式,直接得到一個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ù)打磨多遍,真心不易,如果覺得還不錯,你能轉(zhuǎn)發(fā)、留言或在看支持一下嗎?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容