此篇整理了我常用的Python 3語法
都是為了容易被理解、被修改和被擴充
先介紹String和List的操作
之後會加上幾個好用的package
至於書中在教的decorator、generator
我認為初學者還沒有機會實用到,就不列在這邊
# Don't use (1 < x and x < 10)
x = 5
if 1 < x < 10:
print(x)
# Shorten if else
x = 10
y = 0 if x > 5 else 1
x = 0 if x > 5 else x # 可用於硬要將if弄成一行,但沒有else需求者
print(y)
# Shorten if else when return
def check(x):
return True if x > 10 else False
# Check if string in string
x = 'Hello Jarvus'
if 'Jarvus' in x and 'God' not in x:
print(x)
# Check if string in list
x = ['Hello', 'I am', 'Jarvus']
if 'Jarvus' in x and 'God' not in x:
print(x)
# Concatenate string, f-string works since python 3.6
x = 3000
y = 'Love you ' + str(x) # 此作法每加一個都要重新產生物件,最耗記憶體
z = f'Love you {x}'
i = ''.join(['Hello', ' ', 'Jarvus'])
print(z)
print(i)
# Check is None, don't use (x == None and y != None)
x = None
y = 10
if x is None and y is not None:
print(x)
print(y)
# List comprehension, extract values
x = [{'name': 'Jarvus'}, {'name': 'Tony'}, {'name': 'Stark'}]
y = [i['name'] for i in x]
print(y)
# List comprehension, extract values with conditions
x = [{'name': 'Jarvus', 'id': 1}, {'name': 'Tony', 'id': 2}, {'name': 'Stark', 'id': 3}]
y = [i['name'] for i in x if i['id'] < 3]
print(y)
# Extract string, [3:7] which is element 3~6
x = 'HelloJarvus'
print(x[:5]) # 從頭到第4個字
print(x[3:7]) # 第3個至第6個字
print(x[5:]) # 第5個至最後
# Get the last item in string or list, use -1, -2...
x = 'Hello Jarvus'
y = [1, 2, 3]
print(x[-2])
print(y[:-1])
# Multiple assignment for swap or replace
x, y = 1, 2
x, y = y, x
print(x)
print(y)
# Check if number is wanted, don't use (x == 1 or x == 3 or x == 5)
x = 1
if x in [1, 3, 5]:
print(x)
# Use lambda function as def
add = lambda x : x+1
def add(x):
return x+1
# 以上兩個完全相同,輸入 x、返回 x+1
★ 推薦:博客來試閱 ★