2. Python數據分析開發工具及工作流程
本章内容
-
介紹
-
安装
-
集成開發環境 IDE
-
啟動第一個 Python 應用程式
-
位元組碼解釋 Bytecode interpreter
• 變數、字串、數位、註釋 Variable, String, Number, Comment
-
清單 & 元組 List & Tuple
-
If 語句
-
循環(反覆運算)Loop(iteration)
-
字典和集 Dictionary and Set
-
功能 Function
-
Lambda
-
裝飾 Decorator
-
命名空間
-
可變範圍 Variable Scope
介紹
• 1991 年首次作為 Python 0.9.0 啟動。最新的 Python 版本是 3.12
-
高級程式設計語言
-
面向物件
-
全面的標準庫和大量外部封裝
-
禪宗設計理念
美麗總比醜陋好
顯式比隱式好
簡單勝於複雜
可讀性很重要
Python 受歡迎程度
Top Programming Languages: Rankings In Comparison
| Index | 1st | 2nd | 3rd | 4th | 5th |
| IEEE Spectrum | Python | Java | C | C++ | JavaScript |
| GitHut 2.0 (Pull Requests) | JavaScript | Python | Java | Go | Ruby |
| GitHut 2.0 (Pushes) | JavaScript | Python | Java | C++ | PHP |
| RedMonk | JavaScript | Python | Java | PHP | C++/C# |
| PYPL | Python | Java | Javascript | C# | C/C++ |
| TIOBE | C | Python | Java | C++ | C# |
ChatGPT History
blog.bytebytego.com
Python 系列
-
Cpython:用 C 編寫的 Python 的“預設”實現
-
Ipython:用於數據科學,包含筆記本伺服器,使用者友好
-
Jython:Python 實現,使使用 Java 變得非常容易
-
IronPython:.NET 框架庫,完全用 C# 編寫。
-
PyPy:JIT(即時編譯器)實現
-
PythonNet:.NET 公共語言運行時(CLR)
-
Cython:靜態編譯器,包括調用 C 函數的綁定
-
脾氣暴躁:實驗性 Python 運行時和原始程式碼轉編譯器
-
MicroPython:用 C99 編寫的編譯器和運行時。它在微控制器上運行
本課程中的 Python 和安裝
-
https://www.python.org/
-
最新:Python 3.12.3
-
安裝可能因操作系統而異。
-
macOS 64 位通用 2 / Windows 安装程式(64 位)/ 或其他適合您的作業系統
按兩下已安裝資料夾中的 IDLE
Double-click IDLE in the installed folder
• This is python original shell for editing code
Open your terminal, type python
• This is terminal shell for editing code
IDE 和編輯器
IDE Integrated Development Environment 代表集成開發環境
- 說明程式員高效開發軟體代碼的軟體應用程式
常用 IDE
-
Visual Code Studio – 由 Microsoft 創建。免費使用。一些外掛程式成本
-
PyCharm – 由 JetBrains 创建。社區版/專業版
-
Sublime Text3
-
Spyder
其他 shell 編輯器
Vim:預裝在 MacOS 和 UNIX 系統中。可用於語法高亮、代碼完成、調試、重構等的外掛程式。
打開 Python IDLE,新建檔,
Open Python IDLE, New File, In the editor, code print("Hello World!") Save as the file named hello.py
在「運行」選項卡中,按兩下執行模組。你會看到 Hello World!
如何執行代碼
位元組碼解碼 Bytecode Interpreter
-
CPython 位元組碼解釋器(又名虛擬器 virtual machine)
-
在 Python/ceval.c 中,位元組碼解釋器的工作是執行 Python 代碼。
-
它的主要輸入是一個代碼對象,儘管這不是解釋器的直接參數。
-
解釋器被結構為一個(遞歸)函數,採用線程狀態(tstate)和堆棧幀(frame)。
https://devguide.python.org/internals/interpreter/
變數
Python IDLE shell 可以將其用於行基編碼,這意味著它可以逐行編譯代碼。我們方便嘗試它的編碼。
但是,如果您想保存代碼或代碼行很長,則最好將代碼保存在 *.py
我們可以將文本“Hello World!”存儲到一個名為 message 的變數中並列印出來。
• 變數是帶有標籤的框,您可以在其中儲存值。
-
在 C 等其他程式設計語言中,您需要定義每種變數,例如整數,float,char,string...
-
在 Python 中,您不需要這樣做,因為 Python 會處理它。
如果你用雙引號或單引號來引號某個字元,Python 就會知道它是一個字符串!
Variable message
拆解函数 Disassemble a function
-
讓我們打開 Visual Studio Code,並編輯一個名為 say_hello.py 的函數
-
在終端中,pip install dis 安裝 dis。
-
通過 dis.dis 函數,我們拆解 say_hello 並能夠
查看位元組碼的樣子。我們稍後將詳細討論功能。
hello.py > ...
import dis # import the dis module
def say_hello(): # define a function say_hello
print("Hello World!")
say_hello() # call the function say_hello
dis.dis(say_hello) # disassemble the function say_hello
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL COMMENTS
~/m/PythonCode / Main 210 /Users/honcylee/.pyenv/versions/3.10.5/
bin/python /Users/honcylee/mpyroj/PythonCode/hello.py
Hello World!
4 0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Hello World!')
4 CALL_FUNCTION 1
6 POP_TOP
8 LOAD_CONST 0 (None)
10 RETURN_VALUE
~/m/PythonCode
3.10.5
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello World!
3 0 RESUME 0
4 2 LOAD_GLOBAL 1 (NULL + print)
12 LOAD_CONST 1 ('Hello World!')
14 CALL 1
22 POP_TOP
24 RETURN_CONST 0 (None)
有關 dis 的其他資訊:
https://docs.python.org/3/library/dis.html
有關 Python 編譯器的其他資訊:
https://devguide.python.org/internals/compiler/
字串 String
字串是一系列字元。
如:
“你好,世界!”
‘你好,世界!’
“陳大文 30 歲了”
'蘋果每個 HK$5'
"I borough David's book"
"123"
Python 有很多內置 方法。Method 是處理類的函數。
type(message)將顯示消息的類型
| type(message) <class 'str'>
嘗試在消息后添加 .upper() 或 .lower()。
Python 將改變情況。
>>> | print(message.upper())
HELLO WORLD!
>>> | print(message.lower())
hello world!!
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
HELLO WORLD!
hello world!
整數 Integer
Integers You can add (+), subtract (-), multiply (*), and divide (/) integers in Python.
2+3 5 34 12 12-2 10 10/2 5.0 Float 1/3 Python calls any number with a decimal 0.33333333333333333 2.35.4 12.42
數位下劃線
• 寫長數位時,可以使用下劃線對數字進行分組,使大數位更具可讀性
>>> | hk_population = 7_380_000
>>> | print(hk_population)
7380000
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
7380000
多重分配
- 只需使用一行即可將值分配給多個變數。
>>> | a, b, c = -2, 3.5, 6.0
>>> | print(f"a: {a}, b:{b}, c:{c}")
...
a: -2, b:3.5, c:6.0
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
a: -2, b:3.5, c:6.0
常數 Constant
- 常量就像一個變數,其值在程序的整個生命週期中保持不變。在名稱中使用全部大寫字母。
評論 Comment
註解 在大多數程式設計語言中是一項非常有用的功能。
這將有助於你和你的團隊進行編碼。在註釋前使用 #,或對多行註釋使用三引號。
hello.py - /Users/honcylee/myproj/PythonCode/hello.py (3.11.2)
<h2 id="h-36-My-first-Python-code">My first Python code</h2>
print("Hello World!")
"""
This is
multi-rows
comment
"""
MAX_RETRY_TIMES = 10
print("Max times I can try: ",MAX_RETRY_TIMES)
|
Ln:13 Col:0
Type "help", "copyright", "credits" or "license" for more information
"""
RESTART: /Users/honcylee/myproj/PythonCode/hello.py
Hello World!
Max times I can try: 10
>>>
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello World!
Max times I can try: 10
清單 List
清單是按特定順序排列的項的集合。
>>> students = ['Alex', 'Bob', 'Charlie', 'David', 'Elle']
>>> print(students)
['Alex', 'Bob', 'Charlie', 'David', 'Elle']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
['Alex', 'Bob', 'Charlie', 'David', 'Elle']
訪問清單中的元素
清單是有序集合,因此您可以按位置或索引存取清單中的任何元素。第一個索引是[0]
>>> print(students[0])
Alex
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello World!
Max times I can try: 10
['Alex', 'Bob', 'Charlie', 'David', 'Elle']
Alex
追加清單的元素
>>> students.append('Fion')
>>> print(students)
['Alex', 'Bobby', 'Charlie', 'David', 'Elle', 'Fion']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
['Alex', 'Bob', 'Charlie', 'David', 'Elle']
Alex
['Alex', 'Bob', 'Charlie', 'David', 'Elle', 'Fion']
在清單中插入元素
>>> students.insert(2, 'Carr')
>>> print(students)
['Alex', 'Bobby', 'Carr', 'Charlie', 'David', 'Elle', 'Fion']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
['Alex', 'Bob', 'Carr', 'Charlie', 'David', 'Elle', 'Fion']
從清單中刪除元素
>>> del students[1]
>>> print(students)
['Alex', 'Carr', 'Charlie', 'David', 'Elle', 'Fion']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
['Alex', 'Carr', 'Charlie', 'David', 'Elle', 'Fion']
⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: invalid syntax (
, line 1)),原因見 OCR_run_report.md
使用 sort()對清單進行永久排序
>>> students.sort(reverse=True)
>>> print(students)
['Fion', 'Elle', 'David', 'Charlie', 'Carr', 'Alex']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
['Fion', 'Elle', 'David', 'Charlie', 'Carr', 'Alex']
使用 sorted()暫時對清單進行排序
>>> print(sorted(students))
['Alex', 'Carr', 'Charlie', 'David', 'Elle', 'Fion']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
['Alex', 'Carr', 'Charlie', 'David', 'Elle', 'Fion']
使用 len()尋找清單的長度
>>> students
['Fion', 'Elle', 'David', 'Charlie', 'Carr', 'Alex']
>>> len(students)
6
清單可以是數位
>>> students_age = [25, 30, 28, 45, 35, 60]
>>> students_age
[25, 30, 28, 45, 35, 60]
元 Tuple
元組看起來就像一個清單,只是你使用括弧而不是方括弧。定義元組后,可以使用每個項的索引訪問單個元素,就像訪問清單一樣。
>>> department = ('Human Resources', 'Sales', 'Marketing', 'Accounting')
>>> print(department)
('Human Resources', 'Sales', 'Marketing', 'Accounting')
>>> type(department)
<class 'tuple'>
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
('Human Resources', 'Sales', 'Marketing', 'Accounting')
<class 'tuple'>
訪問元組比訪問清單快得多。
但是你不能改變現有元組中的元素!!
>>> department[0]='HR'
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
department[0]='HR'
TypeError: 'tuple' object does not support item assignment
⚠️ 本頁有 3 段未能本地執行(#3: SyntaxError: invalid syntax (
, line 1); #4: SyntaxError: invalid syntax ( , line 1); #6: SyntaxError: invalid syntax ( , line 1)),原因見 OCR_run_report.md
清單 vs 元組 vs 字串
Lists vs. Tuples vs. Strings
- Creation
x = [a1, a2, a3, ...]
Can contain anything
- len(x) is length
- Supports slicing
Example: x[1:2]
x[i] is an element
- Can concatenate
y = x + [1, 2]
Makes a new list
- Is mutable
x.append(5)
- Creation
x = (a1, a2, a3, ...)
Can contain anything
- len(x) is length
- Supports slicing
Example: x[1:2]
x[i] is an element
- Can concatenate
y = x + (1, 2)
Makes a new tuple
- Is not mutable
- Can concatenate
y = x + ' World'
Makes a new string
- Is not mutable
字典和集 Dict and Set
除清單和元組外,字典和集合是常用的數據類型。
詞典(dict)
與由一系列數字索引的序列不同,字典由鍵索引,鍵可以是任何不可變的類型;字串和數字始終可以是鍵。
字典是{}中的一組鍵值對
Dictionary
phonebook = {
"Alex": "77778888",
"Cherry": "33334444",
"Bob": "55556666",
}
type(phonebook)
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
<class 'dict'>
dict
⚠️ 本頁有 1 段未能本地執行(#1: IndentationError: unexpected indent (
, line 2)),原因見 OCR_run_report.md
訪問字典中的值
使用 list()列出所有键。
使用 sorted()對清單進行臨時排序
1 phonebook
{'Alex': '77778888', 'Bob': '55556666', 'Cherry': '33334444'}
1 list(phonebook)
['Alex', 'Cherry', 'Bob']
1 sorted(phonebook)
['Alex', 'Bob', 'Cherry']
1 phonebook["Alex"]
'77778888'
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
'77778888'
添加、更改和删除 <key : 值>
使用 dict_name[<new key>] = "<new value>" 添加 new <key : value>
如果密鑰已存在,Python 将更新該值。
删除 del><.
1 phonebook["David"] = "88889999"
1 phonebook["Cherry"] = "55554444"
1 phonebook
{'Alex': '77778888',
'Cherry': '55554444',
'Bob': '55556666',
'David': '88889999'}
1 del phonebook["Bob"]
1 phonebook
{'Alex': '77778888', 'Cherry': '55554444', 'David': '88889999'}
建立 dict()構造
dict()構造函數直接從鍵值對序列構建字典
<h3 id="h-40-construct-dict-with-sequences-of-key-val">construct dict with sequences of key-value pairs</h3>
dict([("Edgar", "11112222"), ("Fanny", "33339999")])
'Edgar': '11112222', 'Fanny': '33339999']
<h3 id="h-40-construct-dict-with-specify-pairs-using-">construct dict with specify pairs using keyword arguments</h3>
dict(Edgar="11112222", Fanny="33339999")
'Edgar': '11112222', 'Fanny': '33339999']
<h3 id="h-40-or-more-simplicity">or more simplicity</h3>
{ "Edgar": "11112222", "Fanny": "33339999" }
'Edgar': '11112222', 'Fanny': '33339999'
⚠️ 本頁有 2 段未能本地執行(#1: SyntaxError: invalid character '、' (U+3001) (
, line 1); #2: SyntaxError: unmatched ']' ( , line 4)),原因見 OCR_run_report.md
與其他詞典合併 Merge with other dict
Merge two dict
In Python 3.9.0 or greater
1 phonebook = phonebook | dict(Edgar="11112222", Fanny="33339999")
In Python 3.5 or greater
1 phonebook = {**phonebook, **dict(Edgar="11112222", Fanny="33339999")}
注意:**變數之前表示指標的指標,這可能是早期的 Python 邏輯。
使用 items() 方法循環 dict (Looping a dict with items() method)
for k, v in phonebook.items():
print(k, v)
Alex 77778888
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Alex 77778888
Cherry 55554444
David 88889999
Edgar 11112222
Fanny 33339999
for k, v in phonebook.items():
print(k, v)
Alex 77778888
Cherry 55554444
David 88889999
Edgar 11112222
Fanny 33339999
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Alex 77778888
Cherry 55554444
David 88889999
Edgar 11112222
Fanny 33339999
我們稍後將討論 for 迴圈。
⚠️ 本頁有 1 段未能本地執行(#2: SyntaxError: invalid syntax (
, line 1)),原因見 OCR_run_report.md
集合 Set
集合是没有重複元素的無序集合。
大括弧 {} 或 函数可用於創建集合。
讓我們創建一個集合,看看 Python 如何處理它。
基本用途包括成員資格測試和消除重複條目。
1 fruits = {"cherries", "apple", "banana", "durian", "banana"}
2 type(fruits)
set
1 print(fruits)
{'durian', 'banana', 'cherries', 'apple'}
1 fruits
{'apple', 'banana', 'cherries', 'durian'}
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
{'apple', 'durian', 'banana', 'cherries'}
{'apple', 'durian', 'banana', 'cherries'}
合併集 union(),intersection()
1 more_fruits = {"fig", "grape"}
1 fruits = fruits.union(more_fruits)
2 fruits
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
{'grape', 'banana', 'fig', 'cherries', 'apple', 'durian'}
{'apple', 'banana', 'cherries', 'durian', 'fig', 'grape'}
Union
fruits = {'apple', 'banana', 'cherries', 'fig', 'grape'}
more_fruits = {"fig", "grape", "melon"}
fruits = fruits.intersection(more_fruits)
fruits
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
{'grape', 'fig'}
{'fig', 'grape'}
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
{'grape', 'fig'}
字典和集合使用 Hash 來實現其尋找和置入。
哈希函數是將給定的數位或字母數位鍵轉換為小的實際整數值的函數。
清單、元組、字典、集
| LIST | TUPLE | DICTIONARY | SET |
| Allows duplicate members | Allows duplicate members | No duplicate members | No duplicate members |
| Changeable | Not changeable | Changeable, indexed | Cannot be changed, but can be added, non -indexed |
| Ordered | Ordered | Unordered | Unordered |
| Square bracket [ ] | Round brackets ( ) | Curly brackets{ } | Curly brackets{ } |
語句和表達式 Statement and Expression
在官方 Python 文件中,您可能經常看到這兩個詞。
-
語句 Statement:是 Python 解釋器可以執行的指令。語句是具有效果(如創建變數或顯示值)的最小可執行代碼單元。
-
表達式 Expression:是值、變數、運算元和函數調用的組合。表達式總是計算(計算)自身或返回一些結果。
if 語句
if 語句用於條件執行。
- 它通過評估來精確選擇其中一個套件
一個接一個地表達,直到發現一個為 true,然後執行該套件。
- 如果
,請執行 。
例:
if_staement.py > ...
<h1 id="h-45-If-statement">If statement</h1>
a, b = 1, 2
if a > b:
print("a is greater than b")
elif a < b:
print("a is smaller than b")
else:
print("a is equal to b")
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
a is smaller than b
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL
對於某些複雜的情況,在編碼之前起草邏輯序列是個好主意。
For 迴圈 (for loop)
迴圈是計算機自動執行重複性任務的最常見方式。在許多程式設計語言中,有時它稱為反覆運算。
現在,我們切換到使用 Visual StudioCode 來編寫更長的應用程式。
這是一個使用清單的簡單 for 迴圈。列印清單中的每個元素。注意壓痕!
loop.py > ...
<h1 id="h-46-Loop">Loop</h1>
stocks = ['AAPL', 'GOOG', 'MSFT', 'AMZN']
for stock in stocks:
print(stock)
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
AAPL
GOOG
MSFT
AMZN
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL COMMENTS + pyenv shell 3.10.5
/Users/honcylee/.pyenv/versions/3.10.5/bin/python /Users/honcylee/myproj/PythonCode/Loop.py
= ~/m/PythonCode main pyenv shell 3.10.5
= ~/m/PythonCode main /Users/honcylee/.pyenv/versions/3.10.5/bin/python /Users/honcylee/myproj/PythonCode/loop.py
AAPL
GOOG
MSFT
AMZN
= ~/m/PythonCode
3.10.5
⚠️ 本頁有 1 段未能本地執行(#2: SyntaxError: invalid syntax (
, line 1)),原因見 OCR_run_report.md
使用元組迴圈 Loop using tuple,也是同樣的做法。
loop.py > ...
<h1 id="h-47-Loop">Loop</h1>
2
fruits = ('apple', 'banana', 'orange')
for fruit in fruits:
print(fruit)
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL COMMENTS
in/python /Users/honcylee/myproj/PythonCode/loop.py
apple
banana
orange
~/m/PythonCode > main ?8
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
apple
banana
orange
使用範圍迴圈。
loop.py > ... 1 # Loop 2 3 for i in range(5): 4 print(i)
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL ( in/python /Users/honcylee/myproj/PythonCode/loop.py 0 1 2 3 4 ~/m/PythonCode > main ?8
while 迴圈
而迴圈可以包括 1 個或多個變數作為迴圈條件。
loop.py > ...
<h1 id="h-48-Loop">Loop</h1>
a, b = 1, 5
while a < b:
print(a)
a += 1
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL COI
~/m/PythonCode /Users/honcylee
in/python /Users/honcylee/myproj/PythonCode/loop.py
1
2
3
4
~/m/PythonCode
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
1
2
3
4
或者,您可以肯定地使用 while True 作為開始迴圈,並以 break 結束迴圈。
loop.py > ...
<h1 id="h-48-Loop">Loop</h1>
a, b = 1, 5
while True:
print(a)
a += 1
if a == b:
break
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL CC
~/m/PythonCode /Users/honcyle
in/python /Users/honcylee/myproj/PythonCode/loop.py
1
2
3
4
~/m/PythonCode
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
1
2
3
4
while 迴圈
功能 Function
當您需要執行一些可能需要多次執行的任務時,您應該定義一個函數以更快地實現和代碼維護。
def say_hello():
"""A Function to Say Hello"""
print("Hello!")
4
say_hello()
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello!
Hello!
def 是定義函數的關鍵字。say_hello 是函數的名稱。
您可以使用三引號註釋函數。名為 docstring 的註釋。
函數的正文應縮進。例如,這裡只有一行。
按函數的名稱調用(執行)函數。別忘了支架!
函數中的參數 Argument in function
我們可以將參數(或字串)傳遞給函數,以便函數可以處理。
def say_hello(someone):
"""Say Hello to someone"""
print(f"Hello {someone}!")
4
say_hello("Honda")
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello Honda!
Hello Honda!
您可以放置 docstring 來註釋參數。使用 help(say_hello)查看函數的使用方式。此外,一些文檔工具(如 Sphinx 或 IDE PyCharm)可以識別它以用於未來的文件工作。
📁 Image_20261118_0002.pdf(p.51–100)
def say_hello(someone) -> "input name" : """Say Hello to someone""" print(f"Hello {someone}!") say_hello("Honda") Hello Honda!
help(say_hello) Help on function say_hello in module main': say_hello(someone) -> 'input name' Say Hello to someone
函數中的參數
一個函數,用於將 2 個輸入參數相乘。
def multiply(x, y):
return x * y
print(multiply(3, 4))
print(multiply(4, 5))
12
20
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
12
20
函數 *args 中的參數
您還可以定義一個函數來處理未知數量的參數。正如我們的函數計算輸入數位的總和一樣。
*args 稱為位置參數,元組包含數位。
def sum_num(*args):
total_args = 0
for arg in args:
total_args += arg
return total_args
print(sum_num(1))
print(sum_num(1,2,3))
print(sum_num(1,2,3,2))
1.
6
8
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
1
6
8
函数 **kwargs 中的参数
**kwargs 稱為關鍵字參數。它的工作原理類似於位置參數。區別在於 **kwargs 用於鍵和值對。這些 **kwargs 被放入字典而不是元組中。
def my_setting(**kwargs):
setting = []
for item in kwargs.items():
setting.append(item)
return setting
print(my_setting(unit_tag = "Rebel", shoot_range = 100, bullet_num = 24))
print(my_setting(bullet_num = 50))
['unit_tag', 'Rebel'), ('shoot_range', 100), ('bullet_num', 24)]
['bullet_num', 50)]
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
[('unit_tag', 'Rebel'), ('shoot_range', 100), ('bullet_num', 24)]
[('bullet_num', 50)]
使用 *args 和 **kwargs 進行函數
當然,您可以在函數的參數中同時添加 *args 和 **kwargs。
注意:*args 的作用類似於元組;**kwargs 的行為類似於 dict
def more_setting(*args, **kwargs):
for arg in args:
print(arg)
for item in kwargs.items():
print(item)
return
more_setting(1,2,3, lang='python', group='advance')
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
1
2
3
('lang', 'python')
('group', 'advance')
在函數中返回多個值
函數可以通過元組返回多個值。您可以一一分配它們。在本課程後面的一些 Python 科學庫中,您可能會看到這種用法。
def my_func():
return 1, 2, 3
a, b, c = my_func()
print(a)
print(b)
print(c)
1
2
3
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
1
2
3
Lambda(無記名功能)
在某些情況下,您希望避免繁瑣的函數定義。那麼 Lambda(也稱為內聯函數)可能會有所說明。其他語言可以調用此匿名函數。
def add_x_y(x,y): return x + y add_x_y(4, 5) 9 x_y_add = lambda x,y : x + y x_y_add(4,5) 9
單行句式 one liner
有一些速記編碼,如 Python 中的 lambda。
這三種方法的工作原理相同。第二個和第三個有一個典型的名稱 - 清單理解。這是處理清單數據的快速方法。
1 x = [1, 2, 3, 4, 5]
2 y = []
3 for a in x:
4 if a % 2 == 0: # Check even number
5 y.append(a)
6 y
[2, 4]
1 x = [1, 2, 3, 4, 5]
2 y = [a for a in x if a % 2 == 0]
3 y
[2, 4]
1 [a for a in [1, 2, 3, 4, 5] if a % 2 == 0]
[2, 4]
功能機制
def fl():
print("Hello")
f1()
print(f1)
Hello
<function f1 at 0x112cfe3a0>
In Python the functions have equal status with other objects. Functions can be assigned to variables, stored in collections, created and deleted dynamically, or passed as arguments.
⚠️ 本頁有 1 段未能本地執行(#1: IndentationError: expected an indented block after 'for' statement on),原因見 OCR_run_report.md
import dis
dis.dis(f1)
LOAD_GLOBAL
LOAD_CONST
CALL_FUNCTION
POP_TOP
LOAD_CONST
RETURN_VALUE
def f1():
print("Hello")
def f2(f):
f()
f2(f1)
Hello
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello
Disassembly the function in bytecode, we may see its routines. The function name was stored in an address like an object.
Let's create another function f2. In f2 function, we pass f1 function as an object.
内部功能
我們也可以在 f1 中寫入 f2。在另一個函數中定義的函數稱為內部函數或嵌套函數。 f1 在這裡是內部函數。
def f2():
def f1():
print("Hello")
f1()
f2()
Hello
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Hello
為了擴展函數的行為,我們可以這樣包裝它。將 f2 換行為 f3。
F2 稱為 裝飾器。
def f2(func):
def f1():
print("Hello")
func()
return f1
def f3():
print("Python")
print(f2(f3))
f2(f3)()
<function f2.<locals>.f1 at 0x112d5dee0>
Hello
Python
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
<function f2.<locals>.f1 at 0x7fde5074f6a0>
Hello
Python
A Python decorator is a function that takes another function as input and extends or modifies its behaviour without changing its source code. Decorators are typically used to add functionality to functions or methods in a clean and reusable purpose. In Python, decorators are applied using the @decorator syntax before the function definition. In python we use @ to denote that it is a decorator for ease of code reading.
def f2(func):
def f1():
print("Hello")
func()
return f1
@f2
def f3():
print("Python")
編寫計時器裝飾器代碼
import time
<h2 id="h-55-Define-the-decorator-function">Define the decorator function</h2>
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.2f} seconds to execute")
return result
return wrapper
<h3 id="h-55-Apply-the-decorator-to-a-function">Apply the decorator to a function</h3>
@timer_decorator
def slow_function():
time.sleep(2)
<h3 id="h-55-Call-the-decorated-function">Call the decorated function</h3>
slow_function()
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
slow_function took 2.00 seconds to execute
命名空間
命名空間是當前定義的符號名稱的集合、以及有關每個名稱引用的物件的資訊。您可以將命名空間視為字典,其中鍵是物件名稱,值是物件本身。每個鍵值對將一個名稱映射到其對應的物件。
四種類型的命名空間 LEGB :
一. 本地:如果在函數內部引用 x,則解釋器首先在該函數的本地最內層範圍內搜索它。
二. 封閉:如果 x 不在局部作用域中,但出現在駐留在另一個函數中的函數中,則解釋器將在封閉函數的作用域中搜索。
三. 全域:如果上述搜索均未結果,則解釋器接下來將查看全域範圍。
四. 内置:如果在其他任何地方都找不到 x,則解釋器會嘗試使用內置作用域。
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
Python 預設名城空間 Python Built-In Namespace
Type
dir(builtins) and you will see a list of 155 of them. You can treat these are reserved name in Python.
The Built-In Namespace
In [14]:
1 dir(builtins)
'print', 'property', 'range', 'repr', 'reversed', 'round', 'runfile', 'set', 'setattr', 'slice', sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
還有更多 https://docs.python.org/3/library/
| Library type | example |
| Built-in function | abs(), add(), int(), list(), dict() |
| Built-in constant | True, False, None, NotImplemented |
| Built-in types | Is, is not, int, float, char, complex, and, or |
| Built-in exception | AttributeError, ImportError, KeyError, RuntimeException |
| Text processing | Format, parse, readline |
| Math function | Math, ceil, comb, floor, isnan, decimal, random |
| And more in https://docs.python.org/3/library/ | |
Python 標準程式庫 standard library
Python 的標準庫非常廣泛,提供了廣泛的功能,如長目錄所示。
該庫包含內置模組(用 C 語言編寫),這些模組提供對系統功能(如檔 I/O)的訪問。
其中一些模組被明確設計為通過將特定於平臺的內容抽象為與平台無關的 API 來鼓勵和增強 Python 程式的可移植性。
您應該熟悉一些內置函數,例如 range(),dict(),print(),sum()。
我們鼓勵您使用這些函數來提高效率(記憶體和速度)編碼。
Built-in Functions
A
abs()
aiter()
all()
any()
anext()
ascii()
E
enumerate()
eval()
exec()
L
len()
list()
locals()
R
range()
repr()
reversed()
round()
F
filter()
float()
M
map()
max()
memoryview()
min()
S
set()
setattr()
slice()
sorted()
G
getattr()
globals()
N
next()
staticmethod()
str()
sum()
super()
H
hasattr()
hash()
help()
hex()
object()
oct()
open()
ord()
T
tuple()
type()
id()
input()
int()
isinstance()
issubclass()
iter()
P
pow()
print()
property()
V
vars()
Z
zip()
- import ( )
數學庫
有一些用於數據分析的常見內置庫。數學一定是其中之一。
1 import math
2
3 print(math.sqrt(9))
3.0
<h1 id="h-59-Returns-x-raised-to-the-power-y">Returns x raised to the power y</h1>
pow(2, 3)
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
8
8
1 print( math.floor(5.9) )
2 print( math.ceil(5.1) )
5
6
1 # Returns an accurate floating point
2 # sum of values in the iterable
3 math.fsum([0.1,0.2,0.3,0.4])
1.0
1 # Returns the remainder when x is divided by y
2 math.fmod(5, 2)
1.0
1 # Returns the factorial of x, x!
2 math.factorial(4)
24
<h2 id="h-60-Euler-number">Euler number</h2>
math.e
2.718281828459045
<h3 id="h-60-Returns-e-x">Returns e**x</h3>
math.exp(1)
2.718281828459045
<h3 id="h-60-Returns-the-natural-logarithm-of-1-x">Returns the natural logarithm of 1+x</h3>
math.log1p(20.0855)
3.0485856004577934
<h3 id="h-60-Return-the-number-of-ways-to-choose">Return the number of ways to choose</h3>
<h3 id="h-60-from-n-items-without-repetition-and">from n items without repetition and</h3>
<h3 id="h-60-NCR-function-math-comb-n-k">NCR function math.comb(n, k)</h3>
math.comb(6, 3)
20
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
20
https://docs.python.org/3/library/math.htm
max(iterable, *, key=None)
max(iterable, *, key=None)
max() a list
max() a dict
min(iterable, *, key=None)
min() a list
min() a dict
Lowest: vov
Lowest: vov
注意:在 Python 世界中,您可能经常看到已翘圈,而不需要像 for 翘圈或 while 循環 tuple、NumPy list、Pandas 系列等。
<h3 id="h-60-Returns-the-logarithm-of-x-to-the-base-b">Returns the logarithm of x to the base b (defaults to e)</h3>
<h3 id="h-60-log-x-b">log[x], b)</h3>
math.log(100, 10)
<h3 id="h-60-Returns-the-base-2-logarithm-of-x">Returns the base-2 logarithm of x</h3>
math.log2(8)
<h3 id="h-60-Returns-the-base-10-logarithm-of-x">Returns the base-10 logarithm of x</h3>
math.log10(1000)
items
without order.
the largest item in an iterable
largest of two or more arguments
variable, *, default, key=None)
9.0, 9, 8, 5, 6, 3, 4, 2, 7, 0}
e = {"Alex": 55, "Bob": 65, "Chris": 60}
ax(stu_score, key = lambda k: stu_score[k])
"Highest key: ", key)
"Highest key's value: ", stu_score[key])
Bob
's value: 65
, 9, 8, 5, 6, 3, 4, 2, 7, -1, -1.0})
ating = {13, 21, 3:5, 4:10, 5:3}
min(prod_rating, key = lambda k: prod_rating[k])
"Lowest vote: ", key)
"Lowest vote count: ", prod_rating[key])
es:
e count: 1
iterable 這個詞。這意味著一個物件可以自 意樣的東西。常見的可反覆運算有 list、
⚠️ 本頁有 3 段未能本地執行(#2: SyntaxError: Invalid star expression (
, line 1); #3: SyntaxError: invalid syntax ( , line 12); #4: SyntaxError: unmatched ')' ( , line 3)),原因見 OCR_run_report.md
內置常用資料分析-枚舉 enumerate()
enumerate(iterable, start=0)
- 函數向 iterable 和 yield(許多引用說“return”,但實際上它 yield) it(枚舉物件)添加一個計數器,這意味著 next()或 for 迴圈返回專案。
1 enumerate([6, 7, 8, 9, 10])
<enumerate at 0x107689040>
1 enumerate(["Alex", "Bob", "Chris"])
<enumerate at 0x1076482c0>
1 enumerate({"Alex":55, "Bob":65, "Chris": 60})
<enumerate at 0x107689300>
Equivalent to:
def enumerate(iterable, start=0):
n = start
for elem in iterable:
yield n, elem
n += 1
start=0,表示第一個計數器為0。您可以設定為1或其他整數。
enumerate()將計數器添加到可反覆運算物件
1 list(enumerate([6, 7, 8, 9, 10]))
[(0, 6), (1, 7), (2, 8), (3, 9), (4, 10)]
1 list(enumerate(["Alex", "Bob", "Chris"]))
[(0, 'Alex'), (1, 'Bob'), (2, 'Chris')]
1 list(enumerate({"Alex":55, "Bob":65, "Chris":60}))
[(0, 'Alex'), (1, 'Bob'), (2, 'Chris')]
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
[(0, 'Alex'), (1, 'Bob'), (2, 'Chris')]
⚠️ 本頁有 2 段未能本地執行(#1: SyntaxError: invalid syntax (
, line 2); #2: IndentationError: expected an indented block after 'for' statement on),原因見 OCR_run_report.md
enumerate()是 Python 按數位計算反覆運算次數和索引值的方法。在 C 語言中,它可以為數位編寫 ++counter 代碼。
stu_result = {"Alex":55, "Bob":65, "Chris": 60}
for count, item in enumerate(stu_result, 1):
print(item, stu_result[item])
print("Total student in record", count)
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Alex 55
Bob 65
Chris 60
Total student in record 3
Alex 55 Bob 65 Chris 60 Total student in record 3
内置用於常見資料分析 - zip()
zip()並行反覆運算多個可反覆運算物件,生成每個可反覆運算物件中有一個專案的元組。它返回一個元組反覆運算器,其中第i個元組包含每個參數反覆運算物件中的第i個元素。
key = ["a", "b", "c", "d"]
value = [1, 2, 3, 4]
print("zip into a list >", list(zip(key, value)))
print("zip into a dict >", dict(zip(key, value)))
zip into a list > [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
zip into a dict > {'a': 1, 'b': 2, 'c': 3, 'd': 4}
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
zip into a list > [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
zip into a dict > {'a': 1, 'b': 2, 'c': 3, 'd': 4}
zip()的性能比在 for 循環中組合專案更有效。
x = (1, 2, 3, 4)
y = (5, 6, 7, 8)
z = (9, 10, 11, 12)
print("zip into a list >", list(zip(x,y,z)))
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
zip into a list > [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
zip into a list > [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
內置用於常見數據分析 - map()
map()傳回一個反覆運算器,該反覆運算器將函數應用於可反覆運算的每個專案,從而產生結果。iterator that applies function
map(功能,可反覆運算,*可反覆運算) 含義:具有一系列參數的映射函數。
import math
number = ((3,4),(4.5,6),(6,8))
def cal_length(x):
return math.sqrt(x[0]**2 + x[1]**2)
list(map(cal_length, number))
[5.0, 7.5, 10.0]
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
[5.0, 7.5, 10.0]
在 map()中使用 lambda 更有效率。
var1 = (1, 1, 1, 1)
var2 = (2, 3, 4, 5)
var3 = (5, 6, 7, 8)
list(map(lambda x, y, z : x + y + z, var1, var2, var3))
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
[8, 10, 12, 14]
[8, 10, 12, 14]
內置用於常見資料分析 - split()
分裂(sep=None,maxsplit=-1)
返回字串中單詞的清單,使用 sep 作為分隔符字串。如果給定了 maxsplit,則最多完成 maxsplit 拆分(因此,清單最多有 maxsplit+1 個元素)。如果未指定 maxsplit 或 -
1,則拆分次數沒有限制(進行所有可能的拆分)。
1 sentence = "Dow Jones Rises 300 Points After \
2 Surprise Drop In Jobless Claims; \
3 Block Crashes 22% On Short Seller Report"
4 words = sentence.split()
5 words
['Dow',
'Jones',
'Rises',
'300',
'Points',
'After',
'Surprise',
'Drop',
'In',
'Jobless',
'Claims';
'Block',
'Crashes',
'22%',
'On',
'Short',
'Seller',
'Report']
1 def count_char(word):
2 return len(word)
3 list(map(count_char, words))
[3, 5, 5, 3, 6, 5, 8, 4, 2, 7, 7, 5, 7, 3, 2, 5, 6, 6]
1 map(count_char, words)
<map at 0x1079ff1c0>
注意:此功能通常用於文本分析和網頁抓取。
⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: invalid syntax (
, line 17)),原因見 OCR_run_report.md
正則表達式 Regular Expression
在 Python 中,正則表達式(正則表示式或 RE)是定義搜尋模式的字元序列。再。
搜索(模式,字串,標誌=0)
正則表達式可用於計算關鍵字,甚至用於啟動 LLM(大型語言模型)原始文本標籤。
import re
pattern = "^Apple"
string = "Apple plans to invest $10Bn in motion picture."
result = re.search(pattern, string)
print("Pattern found: ", result[0]) if result else print("No pattern existed.")
result
Pattern found: Apple
<re.Match object; span=(0, 5), match='Apple'>
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Pattern found: Apple
re.findall(模式,字串,標誌=0)
import re
pattern = "mac"
string = "imac bigMac macbook"
result = re.findall(pattern, string)
print(f"{len(result)} pattern(s) found.") if result else print("No pattern existed.")
result
pattern(s) found.
['mac', 'mac']
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
2 pattern(s) found.
| Character | Description | Example |
| \A | Returns a match if the specified characters are at the beginning of the string | "\AThe" |
| \b | Returns a match where the specified characters are at the beginning or at the end of a word(the "r" in the beginning is making sure that the string is being treated as a "raw string") | r"\bain"r"ain\b" |
| \B | Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word(the "r" in the beginning is making sure that the string is being treated as a "raw string") | r"\Bain"r"ain\B" |
| \d | Returns a match where the string contains digits (numbers from 0-9) | "\d" |
| \D | Returns a match where the string DOES NOT contain digits | "\D" |
| \s | Returns a match where the string contains a white space character | "\s" |
| \S | Returns a match where the string DOES NOT contain a white space character | "\S" |
| \w | Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) | "\w" |
| \W | Returns a match where the string DOES NOT contain any word characters | "\W" |
| \Z | Returns a match if the specified characters are at the end of the string | "Spain\Z" |
正規表示式流行用法:
-
敏感語言檢測
-
垃圾郵件檢測
-
文本分析
-
內網搜索
-
密碼驗證
-
電子郵件驗證
如需瞭解更多資訊,請訪問:https://docs.python.org/3/library/re.html
自然語言工具包:https://www.nltk.org/
命令列介面 Command Line Interface (CLI)
命令列介面(CLI)是一種基於文字的使用者介面(UI),用於執行程式、管理計算機檔案以及與電腦交互。命令列介面也稱為命令行使用者介面、控制台使用者介面和字元使用者介面。
對於許多可以在命令行上運行的可執行命令。比方說,pyenv 總是需要背後有參數。
-h 表示常用說明腳本。
--version 用於顯示版本資訊
〔Tesseract 另讀到 1003 字,經詞彙驗證判定為圖內文字/程式碼雜訊,未收錄;需要時見 OCR_uncertain.md〕
Argparse 模組
這 argparse 模組使編寫變得簡單,使用者友好 命令行介面.該程式定義了它需要的參數,以及 argparse 將弄清楚如何解析這些 sys.argv.
讓我們在 IDE 的檔 power.py 中創建一個簡單的 python 代碼。
power.py > ...
import sys
2
n = int(sys.argv[1])
print(f"power of {n} equals to", pow(n,2))
在命令行中運行代碼。我們在 power.py 后輸入的數位是參數向量。
PROBLEMS OUTPUT DEBUG CONSOLE TERMINAL COMMENTS ~/m/PythonCode main 12 73 python power.py 9 power of 9 equals to 81
通過 HKO API 即時香港天氣
現在,讓我們創建一個有趣的代碼來獲取天文臺的天氣數據。
~/myproj/PythonCode usage: python hkweather.py [-h] [-l LANGUAGE] Hong Kong Weather Forecast香港天氣預報 options: -h, --help show this help message and exit -l LANGUAGE, --language LANGUAGE Language (en, tc) (default: None) ~/m/PythonCode 3.10.5
為了獲取 API 數據,我們需要安裝一個名為 requests 的 HTTP 處理庫。
~/m/PythonCode Collecting requests Using cached requests-2.28.2-py3-none-any.whl (62 kB) Collecting idna<4,>=2.5 Using cached idna-3.4-py3-none-any.whl (61 kB) Collecting charset-normalizer<4,>=2 Downloading charset_normalizer-3.1.0-cp310-cp310-macosx_10_9_x86_64.whl (124 kB) 124.8/124.8 kB 974.8 kB/s eta 0:00:00
⚠️ 本頁有 1 段未能本地執行(#1: IndexError: list index out of range),原因見 OCR_run_report.md
什麼是 API?
API 代表應用程式程式設計介面。這是電腦相互通信的標準。典型的方法是 Get、Post、Put、Delete。典型的數據格式有 json、XML
argparse 是 Python 的庫,用於處理命令行參數
hkweather.py > ...
import requests
from argparse import ArgumentParser, ArgumentDefaultIsHelpFormatter
parser = ArgumentParser(prog='python hkweather.py', description='Hong Kong Weather Forecast香港天氣預報', formatter_class=ArgumentDefaultIsHelpFormatter)
parser.add_argument("-l", "--language", help="Language (en, tc)")
args = vars(parser.parse_args())
def gen_report():
print("Hong Kong Weather Report")
print(forecast['updateTime'])
print("[Forecast]")
print(forecast['forecastDesc'])
print("[outlook]")
print(forecast['outlook'])
try:
language = args["language"]
response = requests.get(f"https://data.weather.gov.hk/weatherAPI/opendata/weather.php?dataType=flw&lang={language}")
forecast = response.json()
gen_report()
except:
print("usage: python hkweather.py [-h] [-l LANGUAGE]")
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
usage: python hkweather.py [-h] [-l LANGUAGE]
從 HKO API 連結獲取數據。 收到 json 檔。然後運行 gen_report。
⚠️ 本頁有 1 段未能本地執行(#1: ImportError: cannot import name 'ArgumentDefaultIsHelpFormatter' from),原因見 OCR_run_report.md
現在讓我們在終端 shell 或 CLI 中測試我們的代碼。首先是說明腳本
#!/n/PythonCode
usage: python hkweather.py [-h] [-l LANGUAGE]
Hong Kong Weather Forecast香港天氣預報
options:
-h, --help show this help message and exit
-l LANGUAGE, --language LANGUAGE
Language (en, tc) (default: None)
英文版報告
http://python/PythonCode
Hong Kong Weather Report
2023-03-24T23:15:00+08:00
[Forecast]
Mainly cloudy with a few showers. Coastal mist at first. Sunny intervals in the morning. There will be more showers and one or two squally thunderstorms later. Temperatures will range between 21 and 26 degrees. Moderate to fresh southeasterly winds, becoming east to northeastern later.
[Outlook]
There will be showers and thunderstorms on Sunday. Temperatures will fall. The minimum temperature will be around 19 degrees early next week. Winds will strengthen gradually and there will still be a few rain patches.
繁體中文版報告
http://PythonCode 2.2 main 2.2.3 python hkweather.py -l tc 3.10.5
Hong Kong Weather Report
2023-03-24T23:15:00+08:00
[Forecast]
大致多雲,有幾陣驟雨。初時沿岸有薄霧。早上短暫時間有陽光,稍後驟雨較多及有一兩陣狂風雷暴,氣溫介乎21至26度。吹和緩至清動東南風,稍後轉吹東至東北風。
[Outlook]
星期日有驟雨及雷暴,氣溫下降。下週初最低氣溫在19度左右,風勢逐漸增強,仍然有幾陣雨。
有關 HKO API 數據集的更多資訊,請 www.hko.gov.hk/en/weatherAPI
香港天文台開放數據 API 文件
數據分析的常見依賴外掛 Common Dependency for Data Analysis
數據分析涉及大量的反覆運算任務,使用 Python 內置的相關包(如 NumPy、Pandas、SciPy)的反覆運算功能絕對可以加快你的工作速度。
許多 Python 內置支援反覆運算物件(list、dict 或元組),使用現有的內置或導入的包進行編碼或修改是一個好習慣,而不是從頭開始編寫所有內容。
⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: invalid syntax (
, line 2)),原因見 OCR_run_report.md
提高性能的方法
-
使用內置函數或特定庫
-
減少 for 迴圈的使用
-
使用理解(squares = [x**2 for x in a])
-
如果可能,請使用元組
-
使用較少的全域變數(改用局部變數)
-
將字串與 .join 連接起來
-
使用產生器處理大量資料(我們將在後面的章節中討論)
-
導入必要的庫或特定功能
從頭開始開發專案之前
始終先發現現有庫!這讓您對最新發展有一些簡要的瞭解。
使用谷歌高級搜索或 duckduckgo 以獲得更好的結果。
Go: gle
Advanced Search
Find pages with...
all these words
this exact word or phrase
any of these words
none of these words
numbers ranging from
to
python image library
参考:
初學者
Python Crash Course a Hands-on Project-based Introduction to Programming, 2nd E, Eric Matthes, NoStarch
中間
Dive Into Python3, Mark Pilgrim, APRESS
進展
Python Cookbook, 3 E, David Beazley, O'Reilly
High Performance Python, 2 E, Micha Gorelick, O'Reilly
Effective Python, 90 Specific Ways to Write Better Python, 2 E, Brett Slatkin, ADDISON-WESLEY
Beautiful is better than Ugly
Special cases
Readability
Now
never
The Zen of python
Sparse is better than dense
Simple
complex
Explicit