不要再寫 for 循環了!

爲什麼要挑戰自己在代碼裏不寫 for loop?因爲這樣可以迫使你去學習使用比較高級、比較地道的語法或 library。文中以 python 爲例子,講了不少大家其實在別人的代碼裏都見過、但自己很少用的語法。

自從我開始探索 Python 中驚人的語言功能已經有一段時間了。一開始,我給自己一個挑戰,目的是讓我練習更多的 Python 語言功能,而不是使用其他編程語言的編程經驗。這讓事情變得越來越有趣!代碼變得越來越簡潔,代碼看起來更加結構化和規範化。下面我將會介紹這些好處。

通常如下使用場景中會用到 for 循環:

幸運的是,Python 已經有很多工具可以幫助你完成這些工作,你只需要轉移你的思路,並以不同的角度來思考它。

通過避免編寫 for 循環,你可以獲得什麼好處:

我們來看一下下面的代碼結構:

# 1
with ...:
    for ...:
        if ...:
            try:
            except:
        else:

在這個例子中,我們正在處理多層嵌套的代碼,這很難閱讀。這個例子使用了多層嵌套的代碼。我在這段代碼中發現它無差別使用縮進把管理邏輯(with, try-except)和業務邏輯(for, if)混在一起。如果你遵守只對管理邏輯使用縮進的規範,那麼核心業務邏輯應該立刻脫離出來。

"扁平結構比嵌套結構更好" - The Zen of Python

可以使用的已有的工具來替換 for 循環

1.List Comprehension / Generator 表達式

我們來看一個簡單的例子。如果你想將一個數組轉換爲另一個數組:

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]

同樣,如果您只想迭代數組中的元素,也可以使用一樣的代碼 Generator Expression。result = (do_something_with(item) for item in item_list)

2. 函數

如果您想要將一個數組映射成另外數組,只需調用 map 函數,就可以用一個更高級、更實用的編程方式解決這個問題。

doubled_list = map(lambda x: x * 2, old_list)

如果要將序列減少爲單個,請使用 reduce

from functools import reduce
summation = reduce(lambda x, y: x + y, numbers)

另外,許多 Python 內置函數都會使用 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

上述兩種方法是很好的處理更簡單的邏輯。更復雜的邏輯怎麼樣?作爲程序員,我們編寫函數來抽離出複雜的業務。相同的想法適用於此。如果你是這樣寫的:

results = []
for item in item_list:
    # setups
    # condition
    # processing
    # calculation
    results.append(result)

顯然你對一個代碼塊添加了太多的責任。相反,我建議你做:

def process_item(item):
    # setups
    # condition
    # processing
    # calculation
    return result
results = [process_item(item) for item in item_list]

如果換成嵌套函數會如何

results = []
for i in range(10):
    for j in range(i):
        results.append((i, j))

換成 List Comprehension 來實現是這樣的:

results = [(i, j)
           for i in range(10)
           for j in range(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 來實現這一點:

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 循環,作弊啊!別急,再看看下面的代碼。

不要自己寫。itertools 會幫你實現了

這個模塊很簡單。我相信這個模塊在大多數場景中可以替換你原先的 for 循環。例如,最後一個例子可以重寫爲:

from itertools import accumulate
a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
resutls = list(accumulate(a, max))

另外,如果要迭代組合序列,則需要使用 product(), permutations(), combinations()。

結論

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/cON4CKylzhO1axMg8gghhw