Python Getting Started
資料來源
- :thumbsup: 為你自己學 PYTHON
- Python @ CodeCademy
- Complete-Python-3-Bootcamp @ GitHub
# 在 REPL 環境下載入某支檔案
$ python -i hello.py
Setup & Installation
PIP
官方文件
- PIP
- Version Specifiers:安裝特定版本的套件
$ pip list # 檢視目前電腦上安裝哪些 python package
$ pip install [package] # 安裝套件
$ pip uninstall [package] # 移除套件
$ pip show [package] # 檢視套件資訊
venv
# 建立 virtual env
# python -m venv [virtual_environment_name]
$ python -m venv .venv # 建立名為 .venv 的 virtual environment
# 啟動 virtual env
# source [virtual_environment_name]/bin/activate
$ source .venv/bin/activate
# 進入 virtual env 後,使用 deactivate 可以離開
> deactivate
# 把目前專案有安裝的套件寫進 requirement.txt 中
$ pip freeze > requirements.txt
# 安裝 requirement.txt 中列出的套件
$ pip install -r requirements.txt
# 解除安裝
$ pip uninstall -r requirements.txt -y
Poetry
參考:[note] Python Poetry @ PJCHENder
VSCode
Getting Started with Python in VS Code @ Youtube
Data Structure Basic
Variable
a = 3
type(a) # int
String
##
# Index and Slice
##
'tinker'[1:4] # 'ink'
'tinker'[1:4:2] # 'ik'
'tinker'[::-1] # 'reknit
##
# Formatting with the .format() method
##
'Good {}, {} Chen!'.format('morning', 'Mr.') # 'Good morning, Mr. Chen!'
'My favorite brand is {}, {}, and {}!'.format('Apple', 'Samsung', 'Google') # 'My favorite brand is Apple, Samsung, and Google!'
'My favorite brand is {2}, {1}, and {0}!'.format('Apple', 'Samsung', 'Google') # 'My favorite brand is Google, Samsung, and Apple!'
'Repeat after me: {0}! {0}! {0}!'.format('Ho') # 'Repeat after me: Ho! Ho! Ho!'
'Good {time}, {title} {name}!'.format(time='morning', title='Mr.', name='Chen') # 'Good morning, Mr. Chen!'
##
# Float Formatting
##
result = 100/777 # 0.1287001287001287
# Old Way, {value:width.precision f}
print("The result was {:1.3f}".format(result)) # The result was 0.129
# Formatted String Literals(f-strings)
name = 'Aaron'
age = 33
print(f'Hello, my name is {name}, and I\'m {age} years old.')
List
[0]*3 # [0, 0, 0]
my_list = [1, 3, 2]
another_list = [4, 6, 5]
# array concat
whole_list = my_list + another_list
whole_list # [1, 3, 2, 4, 6, 5]
# sort
whole_list.sort()
whole_list # [1, 2, 3, 4, 5, 6]
whole_list.reverse()
whole_list # [6, 5, 4, 3, 2, 1]
Dictionary
資訊
Mapping Types - Dict @ Python Doc > Built-in Type
Dictionary 基本操作
建立 Dictionary
- dictionary 的 key 必須要是 hashable object,因此
- 可以是 string、number、bool、fronzenset、function
- 不行是 list、set、dictionary,因為它們都是 mutable types
tuple 是 hashable 的嗎?
能不能是 hashable 的實際上是取決於該資料是不是 immutable 的,因此 tuple 不是 hashable 的,取決於裡面的元素。在 Python 中有一個內建的 hash 函式,用它即可知道某資料是不是 hashable 的。例如,hash((1, 'a', True))
是可以的;但如果 tuple 裡面有 list,hash((1, 'a', [1, 2]))
則會得到 TypeError: unhashable type: 'list'
。
hash 後的值不保證一定一樣
在 Python 內建的 hash
函式中它會回傳 int
,基於某些安全性的理由,Python 會保證在同一次執行時,帶入 hash()
中的 input 相同時,能得到相同的 output,但是如果是不同次執行,則相同的 input 不保證會得到相同的 output,所以盡可能不要用 hash() 後的 hash value 來作為 input 是不是相同的判斷。
- dictionary 的 key order 在 Python 3.5+ 後會依照 insert 時的順序被保持
- dictionary 的 value 可以是 any object,例如,lambda、list、dictionary
# 1. 使用 literal
user1 = {'name': 'John', 'age': 25}
# 2-1. 使用 constructor
user2 = dict(name='John', age=25) # 使用 constructor
# 2-2. 使用 tuple 透過 constructor 建立 dictionary
user_from_tuple = (('name', 'John'), ('age', 25))
user3 = dict(user_from_tuple)
# 2.3 使用 list 透過 constructor 建立 dictionary
user_from_list = [['name', 'John'], ['age', 25]]
user4 = dict(user_from_list)
# 3. 使用 comprehension
user_from_list = [['name', 'John'], ['age', 25]]
user5 = {k: v for k, v in user_from_list}
在 Dictionary 中新增或更新 Key-Value
# 使用 []
user = {'name': 'John', 'age': 25}
user["height"] = 180
# dict.setdefault(key, value)
# 如果存在就不動作,如果不存在就新增,類似建立預設值
user.setdefault('name', 'Aaron') # 因為 name 已經存在,所以值依然會是 'John'
user.setdefault('height', 170) # 因為 height 不存在,所以值會是 170
# 使用 update,如果存在就更新,不存在就新增
user.update({
"height": 180,
"width": 76
})
user |= info # update 也可以改成用 |=
# 使用 unpacking operator
new_user = {
**user,
"height": 180,
"width": 76
}
# 使用 |
user = {'name': 'John', 'age': 25}
info = {"height": 180, "width": 76}
new_user = user | info
取值
user = {'name': 'John', 'age': 25}
user["name"] # "John"
user["foo"] # KeyError: 'foo'
# 使用 get:如果沒有該 key 不會噴錯
# get(key, default=None)
user.get("foo") # None
user.get("foo", "default_value") # default_value
刪除 key 與清空
user = {'name': 'John', 'age': 25}
del user["name"] # 刪除 name 這個 key-value pair
user.clear() # 把 user 中的 key-value pairs 清空,變成 empty dictionary
pop, popitem:把 key-value pair 中 dictionary 中取出(後刪除)
# dict.pop(key, [default_value])
user = {'name': 'John', 'age': 25}
user_name = user.pop("name") # "John",並把 user 中的 {"name": "John"} 移除
user_age = user.pop("age", 30) # 25, 如果沒有 age 這個 key,則用 default value(30)
dict.popitem()
是 LIFO,所以可以當作 stack 使用:
# dict.popitem() 把最後面的一組 key-value pair 拿出來
user = {'name': 'John', 'age': 25}
age_info = user.popitem() # ('age', 25)
複製 dictionary
user = {'name': 'John', 'age': 25}
# 使用 copy
new_user = user.copy()
# 使用 dict
new_user = dict(user)
# 使用 unpacking operator
new_user = {**user}
常用方法
Dict Comprehensions
names = ['Jenny', 'Aaron', 'Sam', 'Grace']
ages = [23, 25, 20, 27]
participants = {k:v for k, v in zip(names, ages)} # {'Jenny': 23, 'Aaron': 25, 'Sam': 20, 'Grace': 27}
dict.fromkeys():從其他 iterable object 建立 dictionary
# 根據字串、串列或 Tuple 來建立 Dict 的 key
# classmethod fromkeys(iterable, value=None, /)
dict.fromkeys(['name', 'age'])
dict.fromkeys(['name', 'age'], '') # {'name': '', 'age': ''}
in:判斷 dictionary 中是否有該 key
user = {'name': 'John', 'age': 25}
"name" in user # True
"foo" not in user # False
unpacking operator (**):可以用來合併 dictionary
defaults = {'color': 'red', 'size': 'medium', 'price': 100}
updates = {'color': 'blue', 'price': 150}
final = {**defaults, **updates} # {'color': 'blue', 'size': 'medium', 'price': 150}
迭代 dictionary
user = {'name': 'John', 'age': 25}
len(user) # 2
# 直接迭代 dictionary 會拿到 key
for key in user:
print(k)
# 取得所有 keys
user.keys() # dict_keys(['name', 'age'])
list(user) # ["name", "age"]
user.values() # dict_values(['John', 25])
list(user.values()) # ['John', 25]
for value in user.values():
print(value)
user.items() # dict_items([('name', 'John'), ('age', 25)])
list(user.items()) # [('name', 'John'), ('age', 25)]
for k, v in user.items():
print(f"{k}: {v}")
警告
要特別留意的是,使用 keys()
、values()
、或 items()
拿到的資料並不是真的帶有 key、value 的 list,而是一個 「view」讓我們可以透過它看到目前 dictionary 的資料。因此即使把它存成變數,一旦原本的 dictionary 改變,這個變數得到的內容也會改變。
Tuple
基本操作
建立 Tuple
# 使用 ()
single = (1,)
mixed = (1, "hello", True)
empty = ()
# 使用 tuple constructor
list_to_tuple = tuple([1, 2, 3]) # (1, 2, 3)
string_to_tuple = tuple("hello") # ('h', 'e', 'l', 'l', 'o')
range_to_tuple = tuple(range(3)) # (0, 1, 2)
Enum
import enum
# 定義 enum
class Color(str, enum.Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
print(Color.RED.value) # red
# 把 enum 轉成 list
colors = [color.value for color in Color]
print(colors) # ['red', 'green', 'blue']
Set
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
set1 - set2 # {1, 2}
set2 - set1 # {6, 7}
set1 & set2 # {3, 4, 5}
set1 | set2 # {1, 2, 3, 4, 5, 6, 7}
set1 ^ set2 # {1, 2, 6, 7}
Operators
Comparisons Operators
1 < 2 < 3 # True
1 < 2 and 2 < 3 # True
1 == 1 or 2 == 2 # True
not ( 1 == 1 ) # False
not ( 400 > 5000 ) # True