首頁  >  文章  >  後端開發  >  挑戰:用Python實現循環的替代方案

挑戰:用Python實現循環的替代方案

WBOY
WBOY轉載
2023-05-07 09:28:071110瀏覽

挑战不再写Python for 循环

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

通常如下使用場景中會用到 for 迴圈:

  • 在一個序列來擷取一些資訊。
  • 從一個序列產生另一個序列。
  • 寫入 for 已成習慣。

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

透過避免寫for 循環,你可以得到什麼好處:

  • 較少的程式碼量
  • 更好的程式碼可讀性
  • #更少的縮排(對Python 還是很有意義的)

我們來看看下面的程式碼結構:

# 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()。

結論

  • 在大多數情況下,您都不需要寫for 迴圈。
  • 你應該避免寫for 迴圈,這樣會有更好的程式碼可讀性。
#

以上是挑戰:用Python實現循環的替代方案的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:51cto.com。如有侵權,請聯絡admin@php.cn刪除