賈維斯的智慧工坊

  • Home
  • About
  • Note
  • Project
  • Experience
  • Service
  • Sitemap


MY | NOTES

  1. 首頁
  2. >
  3. 筆記
  4. >
  5. 分享

Python技巧:新手提升效率的必學語法

Tips for Competitive Programmers(持續更新)
Aug, 2022

此篇整理了我常用的Python 3語法
都是為了容易被理解、被修改和被擴充
先介紹String和List的操作
之後會加上幾個好用的package

至於書中在教的decorator、generator
我認為初學者還沒有機會實用到,就不列在這邊

更多精彩文章
如何改寫程式?MATLAB轉Python總整理
[Python] 程式加速:Cython環境安裝與範例
[心得] 無瑕的程式碼:敏捷軟體開發技巧
[TensorFlow] 環境安裝(Anaconda與GPU加速)
[Python] 速度比較:Numpy與內建函式

技巧 Tips

比較大小時,可以將大於小於放在一起

# Don't use (1 < x and x < 10)
x = 5
if 1 < x < 10:
    print(x)
>> 5

將 if 和 else 寫在同一行

# Shorten if else
x = 10
y = 0 if x > 5 else 1
x = 0 if x > 5 else x 	# 可用於硬要將if弄成一行,但沒有else需求者
print(y)
>> 0
# 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)
>> Hello Jarvus

確認list中有沒有包含某字串,同理可用在判斷某object是否在list中

# Check if string in list
x = ['Hello', 'I am', 'Jarvus']
if 'Jarvus' in x and 'God' not in x:
    print(x)
>> ['Hello', 'I am', 'Jarvus']

將string組合在一起,Python 3.6以後可用f-string,不再需要早期的.format

# 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)
>> Love you 3000
>> Hello Jarvus

確認變數是否存在,常利用在function輸入或回傳值

# 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)
>> None
>> 10

從list中的dict取得所有某key的值

# List comprehension, extract values
x = [{'name': 'Jarvus'}, {'name': 'Tony'}, {'name': 'Stark'}]
y = [i['name'] for i in x]
print(y)
>> ['Jarvus', 'Tony', 'Stark']

從list中的dict取得所有「滿足條件」某key的值

# 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)
>> ['Jarvus', 'Tony']

擷取string中的某個段落

# 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個至最後
>> Hello
>> loJa
>> Jarvus

索引值index還能使用倒數的,如-1是最後一個、-2是倒數第二個

# Get the last item in string or list, use -1, -2...
x = 'Hello Jarvus'
y = [1, 2, 3]
print(x[-2])
print(y[:-1])
>> u
>> [1, 2]

一行賦予多個變數值,可用於交換

# Multiple assignment for swap or replace
x, y = 1, 2
x, y = y, x
print(x)
print(y)
>> 2
>> 1

判斷變數是否為想要的

# 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)
>> 1

利用 lambda 宣告單行的 function

# Use lambda function as def
add = lambda x : x+1
def add(x):
	return x+1
# 以上兩個完全相同,輸入 x、返回 x+1

★ 推薦:博客來試閱 ★
無瑕的程式碼:
敏捷軟體開發技巧守則
Python最強入門邁向頂尖高手之路:王者歸來(全彩版)


← Back to note