三種方案 | 拋棄for循環(huán),讓Python代碼更pythonic !
為什么要挑戰(zhàn)自己在代碼里不寫 for loop?因?yàn)檫@樣可以迫使你去學(xué)習(xí)使用比較高級(jí)、比較地道的語法或 library。文中以 python 為例子,講了不少大家其實(shí)在別人的代碼里都見過、但自己很少用的語法。
自從我開始探索 Python 中驚人的語言功能已經(jīng)有一段時(shí)間了。一開始,我給自己一個(gè)挑戰(zhàn),目的是讓我練習(xí)更多的 Python 語言功能,而不是使用其他編程語言的編程經(jīng)驗(yàn)。這讓事情變得越來越有趣!代碼變得越來越簡潔,代碼看起來更加結(jié)構(gòu)化和規(guī)范化。下面我將會(huì)介紹這些好處。
通常如下使用場景中會(huì)用到 for 循環(huán):
- 在一個(gè)序列來提取一些信息。
- 從一個(gè)序列生成另一個(gè)序列。
- 寫 for 已成習(xí)慣。
幸運(yùn)的是,Python 已經(jīng)有很多工具可以幫助你完成這些工作,你只需要轉(zhuǎn)移你的思路,并以不同的角度來思考它。
通過避免編寫 for 循環(huán),你可以獲得什么好處:
- 較少的代碼量
- 更好的代碼可讀性
- 更少的縮進(jìn)(對(duì) Python 還是很有意義的)
我們來看一下下面的代碼結(jié)構(gòu):
# 1
with ...:
for ...:
if ...:
try:
except:
else:
在這個(gè)例子中,我們正在處理多層嵌套的代碼,這很難閱讀。這個(gè)例子使用了多層嵌套的代碼。我在這段代碼中發(fā)現(xiàn)它無差別使用縮進(jìn)把管理邏輯(with, try-except)和業(yè)務(wù)邏輯(for, if)混在一起。如果你遵守只對(duì)管理邏輯使用縮進(jìn)的規(guī)范,那么核心業(yè)務(wù)邏輯應(yīng)該立刻脫離出來。
"扁平結(jié)構(gòu)比嵌套結(jié)構(gòu)更好" - The Zen of Python
可以使用的已有的工具來替換 for 循環(huán)
1.List Comprehension / Generator 表達(dá)式
我們來看一個(gè)簡單的例子。如果你想將一個(gè)數(shù)組轉(zhuǎn)換為另一個(gè)數(shù)組:
result = []
for item in item_list:
new_item = do_something_with(item)
result.append(item)
如果你喜歡 MapReduce,你也可以使用 map,或者 Python 中的 List Comprehension:
result = [do_something_with(item) for item in item_list]
同樣,如果您只想迭代數(shù)組中的元素,也可以使用一樣的代碼 Generator Expression。result = (do_something_with(item) for item in item_list)
2.函數(shù)
如果您想要將一個(gè)數(shù)組映射成另外數(shù)組,只需調(diào)用 map 函數(shù),就可以用一個(gè)更高級(jí)、更實(shí)用的編程方式解決這個(gè)問題。
doubled_list = map(lambda x: x * 2, old_list)
如果要將序列減少為單個(gè),請(qǐng)使用 reduce
另外,許多 Python 內(nèi)置函數(shù)都會(huì)使用 iterables:
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> all(a)
False
>>> any(a)
True
>>> max(a)
9
>>> min(a)
0
>>> list(filter(bool, a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> set(a)
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
>>> dict(zip(a,a))
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
>>> sorted(a, reverse=True)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> str(a)
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
>>> sum(a)
45
3.Extract Functions or Generators
上述兩種方法是很好的處理更簡單的邏輯。更復(fù)雜的邏輯怎么樣?作為程序員,我們編寫函數(shù)來抽離出復(fù)雜的業(yè)務(wù)。相同的想法適用于此。如果你是這樣寫的:
results = []
for item in item_list:
# setups
# condition
# processing
# calculation
results.append(result)
顯然你對(duì)一個(gè)代碼塊添加了太多的責(zé)任。相反,我建議你做:
def process_item(item):
# setups
# condition
# processing
# calculation
return result
results = [process_item(item) for item in item_list]
如果換成嵌套函數(shù)會(huì)如何:
results = []
for i in range(10):
for j in range(i):
results.append((i, j))
換成 List Comprehension 來實(shí)現(xiàn)是這樣的:
results = [(i, j)
for i in range(10)
for j in range(i)]
如果你的代碼塊需要記錄一些內(nèi)部狀態(tài):
# finding the max prior to the current item
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = []
current_max = 0
for i in a:
current_max = max(i, current_max)
results.append(current_max)
# results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
我們使用 generator 來實(shí)現(xiàn)這一點(diǎn):
def max_generator(numbers):
current_max = 0
for i in numbers:
current_max = max(i, current_max)
yield current_max
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
results = list(max_generator(a))
讀者可能要問 “等等!你在 generator 中用到 for 循環(huán),作弊??!別急,再看看下面的代碼。
不要自己寫。itertools 會(huì)幫你實(shí)現(xiàn)了
這個(gè)模塊很簡單。我相信這個(gè)模塊在大多數(shù)場景中可以替換你原先的 for 循環(huán)。例如,最后一個(gè)例子可以重寫為:
from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))
另外,如果要迭代組合序列,則需要使用product(), permutations(), combinations()。
結(jié)論
- 在大多數(shù)情況下,您都不需要編寫 for 循環(huán)。
- 你應(yīng)該避免編寫 for 循環(huán),這樣會(huì)有更好的代碼可讀性。