自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

挑戰(zhàn)不再寫Python for 循環(huán)

開發(fā) 后端
為什么要挑戰(zhàn)自己在代碼里不寫 for loop?因?yàn)檫@樣可以迫使你去學(xué)習(xí)使用比較高級、比較地道的語法或 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)(對 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)混在一起。如果你遵守只對管理邏輯使用縮進(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è)更高級、更實(shí)用的編程方式解決這個(gè)問題。

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

如果要將序列減少為單個(gè),請使用 reduce

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

另外,許多 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)

顯然你對一個(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),作弊?。e急,再看看下面的代碼。

不要自己寫。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ì)有更好的代碼可讀性。
責(zé)任編輯:龐桂玉 來源: Python編程學(xué)習(xí)圈
相關(guān)推薦

2023-08-25 13:34:02

JavascriptWikipediaSlack

2022-02-21 12:29:01

for循環(huán)前端

2020-06-04 09:18:52

CTOif-else代碼

2018-08-07 15:21:01

CNNRNN循環(huán)神經(jīng)網(wǎng)絡(luò)

2024-07-09 08:21:57

2020-12-15 09:31:58

CTOif-else代碼

2015-03-03 15:37:21

軟件定義網(wǎng)絡(luò)

2010-03-11 14:15:24

Python循環(huán)

2015-10-30 09:36:09

H5崛起

2015-10-30 10:32:18

HTML5高冷小眾

2023-09-21 22:19:03

Python編程語言

2023-09-16 18:48:28

代碼邏輯

2021-08-11 09:00:30

Python基礎(chǔ)循環(huán)

2022-06-21 15:00:01

Python語言循環(huán)方式

2024-05-10 14:46:27

Pythonfor循環(huán)

2021-07-21 14:29:27

Python編程語言軟件開發(fā)

2021-12-09 23:20:31

Python循環(huán)語句

2015-09-14 09:52:02

2023-03-20 07:23:45

Docker開源存儲庫

2020-06-15 08:12:51

try catch代碼處理器
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號