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

5個小技巧,讓你的for循環(huán)瞬間高大上!

開發(fā) 后端
如何讓你的for循環(huán)告別繁復(fù)擁抱簡潔,如何重啟探索Python循環(huán)迭代的大門,希望以下幾個小技巧能夠給你啟發(fā)。

本文轉(zhuǎn)載自公眾號“讀芯術(shù)”(ID:AI_Discovery)

或許每個初學(xué)Python的程序員最早接觸的概念中都有For循環(huán),這一點理所當(dāng)然, for循環(huán)可以在不費吹灰之力的情況下對數(shù)據(jù)執(zhí)行很多操作。

然而,大量的使用for循環(huán)也可能會讓使用者的思維拘泥于簡單的迭代中,而忽略了一些更加高效且簡潔的迭代方法。

如何讓你的for循環(huán)告別繁復(fù)擁抱簡潔,如何重啟探索Python循環(huán)迭代的大門,希望以下幾個小技巧能夠給你啟發(fā)。

Zip:同時在兩個列表中循環(huán)

筆者在實踐中發(fā)現(xiàn)代碼可以同時在兩個數(shù)組中進行循環(huán)。要想在其他的編程語言中做到這一點相對來說難度大很多,這也體現(xiàn)出了Python的簡易性。要達到同時在兩個數(shù)組中進行循環(huán)這一目的,只需使用zip()函數(shù)。

  1. for first,second in zip(array1,array2): 
  2.     print(first) 
  3.     print(second) 

在一個偶整數(shù)序列和一個奇整數(shù)序列中使用這一方法就能體現(xiàn)出這一函數(shù)的功效。

  1. odds = [1,3,5,7,9] 
  2. evens = [2,4,6,8,10] 
  3. for oddnum, evennum in zip(odds,evens): 
  4.     print(oddnum) 
  5.     print(evennum) 

以上函數(shù)輸出的結(jié)果便是:

  1. 10 

In Range函數(shù):編寫C-Style循環(huán)

C-Style似乎看起來有點兒平凡,但它能在循環(huán)中煥發(fā)光彩。

  1. for i in range(10): 
  2.     print(i) 
  3.     if i == 3: 
  4.         i.update(7) 

C語言愛好者可能覺得以上的代碼并不是C-Style循環(huán),但如果不想自己動手編寫迭代函數(shù),以上內(nèi)容已經(jīng)是最完美的形式了。

不過筆者熱衷于“浪費時間”,因此決定編寫一個新的迭代程序來寫出盡可能完美的C-Style循環(huán)。

  1. class forrange: 
  2.  
  3.     def __init__(self, startOrStop,stop=Nonestep=1): 
  4.         if step == 0: 
  5.             raise ValueError('forrangestep argument must not be zero') 
  6.         if not isinstance(startOrStop,int): 
  7.             raise TypeError('forrangestartOrStop argument must be an int') 
  8.         if stop is not None and notisinstance(stop, int): 
  9.             raise TypeError('forrangestop argument must be an int') 
  10.  
  11.         if stop is None: 
  12.             self.start = 0 
  13.             self.stop = startOrStop 
  14.             self.step = step 
  15.         else: 
  16.             self.start = startOrStop 
  17.             self.stop = stop 
  18.             self.step = step 
  19.  
  20.     def __iter__(self): 
  21.         returnself.foriterator(self.start, self.stop, self.step) 
  22.  
  23.     class foriterator: 
  24.  
  25.         def __init__(self, start, stop,step): 
  26.             self.currentValue = None 
  27.             self.nextValue = start 
  28.             self.stop = stop 
  29.             self.step = step 
  30.  
  31.         def __iter__(self): return self 
  32.  
  33.         def next(self): 
  34.             if self.step > 0 andself.nextValue >= self.stop: 
  35.                 raise StopIteration 
  36.             if self.step < 0 andself.nextValue <= self.stop: 
  37.                 raise StopIteration 
  38.             self.currentValue =forrange.forvalue(self.nextValue, self) 
  39.             self.nextValue += self.step 
  40.             return self.currentValue 
  41.  
  42.     class forvalue(int): 
  43.         def __new__(cls, value,iterator): 
  44.             value =super(forrange.forvalue, cls).__new__(cls, value) 
  45.             value.iterator = iterator 
  46.             return value 
  47.  
  48.         def update(self, value): 
  49.             if not isinstance(self, int): 
  50.                 raiseTypeError('forvalue.update value must be an int') 
  51.             if self ==self.iterator.currentValue: 
  52.                 self.iterator.nextValue =value + self.iterator.step 

Filter()函數(shù):只對需要的數(shù)據(jù)進行循環(huán)

在處理大量的數(shù)據(jù)時,使用filter函數(shù)能夠使得數(shù)據(jù)在使用時效果更佳。Filter函數(shù)正如其名,其功效是在對數(shù)據(jù)進行迭代前進行過濾。當(dāng)只需要使用某一范圍內(nèi)的數(shù)據(jù)而且不想再添加一個條件時,filter十分實用。

  1. people = [{"name": "John","id": 1}, {"name": "Mike", "id": 4},{"name": "Sandra", "id": 2}, {"name":"Jennifer", "id": 3}]for person in filter(lambda i:i["id"] % 2 == 0, people): 
  2. ...     print(person) 
  3. ... 
  4. {'name': 'Mike', 'id': 4} 
  5. {'name': 'Sandra', 'id': 2} 

Enumerate()函數(shù):對維度進行索引

在Python中使用枚舉函數(shù)可以讓Python將從數(shù)組中輸出的列表索引進行編號。筆者制作了一個包含三個元素的列表對這一功能進行展示:

  1. l = [5,10,15] 

現(xiàn)在可以利用以下方法來訪問數(shù)組索引:

  1. l[1] 
  2. 10 
  3. l[0] 
  4. l[2] 
  5. 15 

在這些列表中進行枚舉時,維度的索引位置和維度會結(jié)合產(chǎn)生一個新的變量。請注意這一新變量的類型。

Python會自動將這些索引置入一個元組之中,這一點十分奇怪。筆者還是傾向于從只有一個元素的Python庫中獲得這些結(jié)果。還好,我們可以把這些枚舉函數(shù)置入到一個Python庫中。

  1. data = dict(enumerate(l)) 

輸入以上代碼之后就會得出:

  1. >>> data 
  2. {0: 5, 1: 10, 2: 15} 

[[324869]]

圖源:unsplash

Sorted()函數(shù):使用數(shù)據(jù)中進行排序,而非使用前

Sort函數(shù)對于常常需要處理大量數(shù)據(jù)的人來說至關(guān)重要,它將字符串根據(jù)首字母A到B進行排列,將整數(shù)和倍數(shù)自負無窮起由小至大排列。需要注意的是,這一函數(shù)無法用于帶有字符串和整數(shù)或浮點數(shù)的列表。

  1. l = [15,6,1,8] 
  2. for i in sorted(l): 
  3.     print(i) 
  4. 15 

也可以將相反的參數(shù)設(shè)為False來進行逆運算。

  1. for i in sorted(l,reverse = True): 
  2.     print(i) 
  3. 15 

對于可用的最后一個參數(shù),可以使用key函數(shù)。Key是一個應(yīng)用于已知循環(huán)中的每個維度的函數(shù)。而筆者偏向于使用lambda,Lambda會創(chuàng)造一個匿名但仍可調(diào)用的函數(shù)。

  1. l.sort(key=lambda s: s[::-1]) 

寫代碼時,遇到大量的帶有迭代的數(shù)據(jù)在所難免。簡潔成就卓越,這些方法能夠使代碼簡潔明了并且運行起來更快。循環(huán)的世界值得你繼續(xù)探索!

 

責(zé)任編輯:趙寧寧 來源: 讀芯術(shù)
相關(guān)推薦

2014-05-16 11:18:14

瀏覽器ChromeFirefox

2024-12-25 12:00:00

C++解包代碼

2019-04-02 09:23:40

設(shè)計模式前端JavaScript

2009-10-27 09:09:06

Eclipse技巧

2024-01-08 17:09:07

Python解釋器CPython

2022-01-06 22:31:21

Python技巧代碼

2023-05-10 08:32:42

ISlidePPT插件工具

2020-04-20 15:07:50

性能優(yōu)化低效循環(huán)程序

2024-12-31 00:00:30

CursorAI編程

2019-12-03 08:59:13

Windows電腦軟件

2024-02-26 18:11:08

Docker容器鏡像

2017-04-13 11:45:56

報表大數(shù)據(jù)應(yīng)用

2023-02-22 17:51:10

VS code插件技巧

2017-09-08 08:43:39

iOS 11SafariPDF

2009-05-04 09:11:28

GoogleChrome瀏覽器

2024-11-25 18:37:09

2025-05-07 07:17:18

2020-02-26 21:57:09

Lambdajava8方法引用

2020-07-08 17:06:00

Python開發(fā)工具

2018-09-03 14:49:27

Python實戰(zhàn)項目
點贊
收藏

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