文章目錄
-
-
- 基礎入門
- 菜鳥提升
- 基礎晉級
- 高手之路
- 内置包庫
- 奇技淫巧
-
基礎入門
1
python
即在指令行輸入
python
,進入
Python
的開發環境。
2
x = 1+2*3-4/5+6**2
加減乘除四則混合運算,可以當作電腦用了,其中
**
表示乘方。
3
print(x)
即輸出
x
的值,如果感覺麻煩,可以直接輸入
x
,然後回車,也能看到x的值。
4
if x>5 : print(x)
簡單的判斷,如果
x>5
,則列印
x
。
5
for i in range(10): print(i)
簡單的循環,其中
range(10)
表示建立一個可疊代的自然序列,
range(10)
表示
0,1,2...10
。
6
'hello '+"world"
python中可以用單引号或雙引号表示字元串,
+
可以拼接兩個字元串。
7
def addOne(x):return x+1
python中通過
def
來聲明函數,函數名稱和函數主體之間用
:
分隔,聲明上式之後可以直接在指令行中調用。
>>> def addOne(x):return x+1
...
>>> addOne(1)
2
8
x = [1,2,'abc',3,2]
python中可通過
[]
來建立一個清單,清單中的成員可以為任意資料類型。
>>> x = [1,2,'abc',3,2]
>>> x
[1, 2, 'abc', 3, 2]
9
x[0]
python中通過方括号和冒号來進行索引,且索引從0開始。
>>> x[0]
1
10
y = set(x)
set
為集合,集合中不允許存在相同的元素,是以将一個清單轉成集合之後,會删除清單中的重複元素。
>>> y = set(x)
>>> y
{1, 2, 3, 'abc'}
菜鳥提升
11
pip install numpy
在指令行中運作
pip
指令,進行python相關包的安裝。安裝之後,再運作
python
進入python環境。
12
import numpy as np
導入
numpy
包,并給與其
np
的辨別,進而我們可以通過
np.
的形式來調用
numpy
中的函數。
13
x = np.arange(10)
生成一個自然序列,與
range
,但是
np.arange
得到的可進行運算的數組(array)。
>>> x = np.arange(10)
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
14
x**2
沒什麼好說的,隻是示範以下array可以使用運算符。
>>> x**2
array([ 0, 1, 4, 9, 16, 25, 36, 49, 64, 81], dtype=int32)
15
x.tolist()**2
這是一行錯誤的代碼,其中
x.tolist()
是将x從
array
轉成
list
。然後再算其平方,然而清單(list)這種資料格式在python中是不能直接進行計算的,是以報了錯。
>>> x.tolist()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x.tolist()**2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
16-18
>>> if len(x)==5:print(x)
... elif len(x)==10: print(x.tolist()+x)
... else: print(x[0])
...
[ 0 2 4 6 8 10 12 14 16 18]
len
表示擷取
x
的長度,python中通過
==
來判斷二者是否相等。上式表示,如果x的長度等于5,則列印x;或者x的長度為10,則列印
x.tolist()+x
;如果x的長度為其他值,則列印
x[0]
。
由于x的長度是10,是以執行了第2行代碼。而且我們發現,python非常智能地按照
array
的規則計算了
x.tolist()+x
。這說明,當表達式中同時存在
array
和
list
的時候,python會自動将
list
轉為
array
。
19-20
>>> d = {"a":1,"b":2,"c":3}
>>> d["a"]
1
d即為字典,可通過鍵值對的形式進行索引。案例中,
"a","b","c"
為鍵(
key
),
1,2,3
為值(
value
),通過
key
來索引
value
,非常便利。
基礎晉級
21
a = 1,2,3
逗号分隔的變量會預設組成元組,元組會根據等号左邊變量的個數來進行指派。
>>> a = 1,2,3
>>> a
(1, 2, 3)
22
a,b = 1,2
元組可以通過元素對應的位置來進行一一指派,由此而帶來的便利就是可以更快速地交換兩個變量的值。
>>> a,b = 1,2
>>> a
1
>>> b
2
>>> b,a = a,b
>>> b
1
>>> a
2
23
print(f"a={a}")
在python中,字元串前面可有四種字首,其中
f
代表字元串格式化,即format,在f字元串中,大括号内部會自動轉換為變量。
>>> print(f"a={a}")
a=2
24
a = False if a==2 else True
在Python中,
False
和
True
為bool型的兩個值。
在python中,可通過
if...else
構成三元表達式,上式可等價為響應的C語言
a = a==2 ? 0 : 1
。
>>> a = False if a==2 else True
>>> a
False
25
x = [i for i in range(10)]
在python中,可通過
for
循環來建立元組、清單以及字典。
>>> x = [i for i in range(10)]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
26-30
def fac(n):
if n == 0:
return 1
else:
return n*fac(n-1)
這是一個階乘算法。在pyhton中,代碼塊以空格的形式存在。
高手之路
31
fac = lambda n : 1 if n==0 else n*fac(n-1)
這同樣是一個階乘算法,與26-30表示的是同一個函數。此即
lambda
表達式,可以更加友善地建立函數。
32
op = {"add":lambda a,b:a+b, "minus":lambda a,b:a-b}
Python中沒有
switch..case
表達式,而字典+lambda表達式可以彌補這一點。上式中,
op["add"]
表示調用函數
lambda a,b:a+b
,即加法;
op["minus"]
表示調用函數
lambda a,b:a-b
,即減法。
正因
lambda
表達式并不需要命名,是以也稱匿名函數。
>>> op = {"add":lambda a,b:a+b, "minus":lambda a,b:a-b}
>>> op["add"](3,4)
7
>>> op["minus"](3,4)
-1
33-34
while a<5:a+=1
else: print(f"a={a}")
while循環大家都十分了解,即當
a<5
時執行
a+=1
的程式。
else
表示當
a<5
不滿足時執行的代碼。
>>> while a<5:a+=1
... else: print(f"a={a}")
...
a=5
35-37
xs = []
for x in range(10): xs.append(x)
else : print(xs)
和
while..else
相似,
for
也有和
else
的組合,其語義也很雷同,表示當執行完
for
循環之後執行
else
的語句。
>>> xs = []
>>> for x in range(10): xs.append(x)
... else : print(xs)
...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
38-40
from matplotlib import pyplot as plt
plt.plot(np.random.rand(10))
plt.show()
from...import
表示從
matplotlib
中導入
pyplot
。
matplotlib
是python中最常用的畫圖包,功能非常強大。
plt.plot
是最常用的繪圖函數。
python
在執行繪圖函數之後,會将圖檔放入記憶體,當使用
plt.show()
之後,才會将其顯示到螢幕上。
>>> from matplotlib import pyplot as plt
>>> plt.plot(np.random.rand(10))
[<matplotlib.lines.Line2D object at 0x00000232FA511B10>]
>>> plt.show()
41-48
class person:
def __init__(self,name):
self.name = name
def selfIntro(self):
print(f"my Name is {self.name}")
@staticmethod
def say(string):
print(string)
盡管python主打函數式,但在python中,一切皆對象。而
class
則可以聲明一個類。
在類中,通過
self
來聲明類成員,類似有些語言中的
this.
。
__init__
為python内置的初始化函數,在類執行個體化之後,會首先運作這個函數。
@staticmethod
為靜态類辨別,靜态類可以不經執行個體而使用。
>>> class person:
... def __init__(self,name):
... self.name = name
... def selfIntro(self):
... print(f"my Name is {self.name}")
... @staticmethod
... def say(string):
... print(string)
...
>>> person.say("hello")
hello
>>> person.selfIntro()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person.selfIntro() missing 1 required positional argument: 'self'
>>> Li = person("Li")
>>> Li.selfIntro()
my Name is Li
>>>
49
xs=[i for i in range(10) if i%2==0]
通過推導式來快速通過篩選來建立清單。
>>> xs=[i for i in range(10) if i%2==0]
>>> xs
[0, 2, 4, 6, 8]
50
d = dict([[1,2],[4,5],[6,7]])
通過
dict
可将清單轉為字典,前提是清單中的元素必須為二進制組。
>>> d = dict([[1,2],[4,5],[6,7]])
>>> d
{1: 2, 4: 5, 6: 7}
内置包庫
51
time.time()
當然前提是要導入
import time
,這其實是個很常用的函數,以時間戳的形式傳回目前的時間。
詳情可檢視python内置時間子產品.
>>> import time
>>> time.time()
1634558595.5172253
52
calendar.prmonth(2021,10)
可列印月曆。。。詳情可參見python列印一整年的月曆
>>> import calendar
>>> calendar.prmonth(2021,10)
October 2021
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
>>>
53
os.listdir(r"c:\Windows")
可傳回檔案夾内部的檔案和子檔案夾。其中
r
辨別字元串中的
\
不用于轉義。
>>> import os
>>> os.listdir(r"c:\Windows")
['addins', 'appcompat', 'apppatch', 'AppReadiness', 'assembly', 'bcastdvr', 'bfsvc.exe', ...
54
glob.glob(r"c:\Windows\*.ini")
可通過通配符傳回檔案夾内部的檔案。
>>> import glob
>>> glob.glob(r"c:\Windows\*.exe")
['c:\\Windows\\bfsvc.exe', 'c:\\Windows\\explorer.exe', 'c:\\Windows\\HelpPane.exe', 'c:\\Windows\\hh.exe', 'c:\\Windows\\notepad.exe', 'c:\\Windows\\py.exe', 'c:\\Windows\\pyw.exe', 'c:\\Windows\\regedit.exe', 'c:\\Windows\\splwow64.exe', 'c:\\Windows\\Wiainst64.exe', 'c:\\Windows\\winhlp32.exe', 'c:\\Windows\\write.exe']
>>>
55-56
urllib
response = urllib.request.urlopen('https://blog.csdn.net/')
html = response.read()
urllib
是python内置的http解析請求庫,是大多數爬蟲學習者接觸的第一個工具。
其中,
read()
用于讀取網頁資料,當然,得到的網頁資料是未解碼資料。
import urllib.request
response = urllib.request.urlopen('https://blog.csdn.net/')
html = response.read()
57-58 正規表達式re
content = html.decode('utf-8')
cn = re.findall(r"[\u4e00-\u9fa5]+", content)
此為正規表達式的簡單應用,
re.findall
表示從字元串
content
中篩選出符合
r"[\u4e00-\u9fa5]+"
要求的值。是以第一步,是通過
utf-8
對content進行解碼。
而在
utf-8
中,漢字的序号為
\u4e00-\u9fa5
;在正規表達式中,
[]
表示符合條件的集合,
+
表示出現任意多個符合條件的字元。
>>> import re
>>> content = html.decode('utf-8')
>>> cn = re.findall(r"[\u4e00-\u9fa5]+", content)
>>> cn[:20]
['部落格', '專業', '技術發表平台', '部落格為中國軟體開發者', '從業人員', '初學者打造交流的專業', '技術發表平台', '全心緻力于幫助開發者通過網際網路分享知識', '讓更多開發者從中受益', '一同和', '開發者用代碼改變未來', '頭部', '廣告', '頻道首頁右側', '打底', '頭部', '廣告', '題目征集', '你出我答', '做']
>>>
59-60 建立視窗程式
tkinter
frame = tkinter.Tk()
frame.mainloop()
其中
frame
即為tkinter建立的視窗,而
mainloop
表示進入視窗的消息循環。
>>> import tkinter
>>> frame = tkinter.Tk()
>>> frame.mainloop()
奇技淫巧
61
judge = lambda a,b,f1,f2 : (f1 if a>b else f2)(a,b)
表示,如果
a>b
則執行
f1(a,b)
,否則執行
f2(a,b)
62
eval('[a,b,c]')
eval
函數會把字元串轉為可執行的表達式。
63
list(zip(*lst))
zip
可以像拉鍊一樣将數組中對應的值縫合起來,以元組的形式重新存儲。根據這個特性,可完成清單的"轉置"。
>>> lst = [[1,2], [3,4], [5,6]]
>>> list(zip(*lst))
[(1, 3, 5), (2, 4, 6)]
64
max(set(lst),key=lst.count)
其中
lst
為清單,
count(i)
是清單的内置函數,表示統計
i
出現的個數。
set
表示将
lst
轉為集合,進而剩排除重複值。
max(set(lst),key=lst.count)
表示通過
lst.count
這個名額來得到
set(lst)
中出現次數最多的那個值——即求衆數。
65
dict(zip(myDict.values(),myDict.keys()))
通過
zip
實作字典的字元串互換操作。
66
[*a,*b]
*可以取出清單中的元素,是以
[*a,*b]
可以起到合并清單的作用。
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> [*a,*b]
[1, 2, 3, 4, 5, 6]
但星号索引的用途不止于此,在函數傳參時也有意想不到的後果
>>> addd = lambda a,b,c : a+b+c
>>> addd(*a)
6
67
{**a,**b}
雙星号可以取出字典中的元素,實作字典合并的功能。
>>> a = {"b":1,"c":2}
>>> b = {"d":3,"e":4}
>>> {**a,**b}
{'b': 1, 'c': 2, 'd': 3, 'e': 4}
同樣,雙星号索引的用途也不止于此
>>> addd(3,**a)
6
68
s == s[::-1]
在python中,對清單或者字元串采用
:
進行索引,例如
a:b
指的是從a到b的資料;當采用雙引号
::
時,引号間的值的意義就發生了變化,例如
a:b:c
表示從a到b,間隔為c的資料。
據此,可以得到
::-1
表示将字元串颠倒過來,據此可以判斷一個字元串是否為回文結構。
盡管這些代碼還沒涉及到多線程等功能(主要是行數比較多),也沒涉及到和類相關的一些功能(也是因為行數多),但如果您全都一目了然或者曾經用過,那麼我願稱君為高手!