或許每一個初學Python的程序員最先接觸的概念中都有For循環,這一點理所固然, for循環能夠在不費吹灰之力的狀況下對數據執行不少操做。程序員
然而,大量的使用for循環也可能會讓使用者的思惟拘泥於簡單的迭代中,而忽略了一些更加高效且簡潔的迭代方法。編程
如何讓你的for循環告別繁複擁抱簡潔,如何重啓探索Python循環迭代的大門,但願如下幾個小技巧可以給你啓發。數組
筆者在實踐中發現代碼能夠同時在兩個數組中進行循環。要想在其餘的編程語言中作到這一點相對來講難度大不少,這也體現出了Python的簡易性。要達到同時在兩個數組中進行循環這一目的,只需使用zip()函數。網絡
for first,second in zip(array1,array2): print(first) print(second)
在一個偶整數序列和一個奇整數序列中使用這一方法就能體現出這一函數的功效。框架
odds = [1,3,5,7,9] evens = [2,4,6,8,10] for oddnum, evennum in zip(odds,evens): print(oddnum) print(evennum)
以上函數輸出的結果即是:機器學習
1 2 3 4 5 6 7 8 9 10
C-Style彷佛看起來有點兒平凡,但它能在循環中煥發光彩。編程語言
for i in range(10): print(i) if i == 3: i.update(7)
C語言愛好者可能以爲以上的代碼並非C-Style循環,但若是不想本身動手編寫迭代函數,以上內容已是最完美的形式了。函數
不過筆者熱衷於「浪費時間」,所以決定編寫一個新的迭代程序來寫出儘量完美的C-Style循環。學習
class forrange: def __init__(self, startOrStop,stop=None, step=1): if step == 0: raise ValueError('forrangestep argument must not be zero') if not isinstance(startOrStop,int): raise TypeError('forrangestartOrStop argument must be an int') if stop is not None and notisinstance(stop, int): raise TypeError('forrangestop argument must be an int') if stop is None: self.start = 0 self.stop = startOrStop self.step = step else: self.start = startOrStop self.stop = stop self.step = step def __iter__(self): returnself.foriterator(self.start, self.stop, self.step) class foriterator: def __init__(self, start, stop,step): self.currentValue = None self.nextValue = start self.stop = stop self.step = step def __iter__(self): return self def next(self): if self.step > 0 andself.nextValue >= self.stop: raise StopIteration if self.step < 0 andself.nextValue <= self.stop: raise StopIteration self.currentValue =forrange.forvalue(self.nextValue, self) self.nextValue += self.step return self.currentValue class forvalue(int): def __new__(cls, value,iterator): value =super(forrange.forvalue, cls).__new__(cls, value) value.iterator = iterator return value def update(self, value): if not isinstance(self, int): raiseTypeError('forvalue.update value must be an int') if self ==self.iterator.currentValue: self.iterator.nextValue =value + self.iterator.step
在處理大量的數據時,使用filter函數可以使得數據在使用時效果更佳。Filter函數正如其名,其功效是在對數據進行迭代前進行過濾。當只須要使用某一範圍內的數據並且不想再添加一個條件時,filter十分實用。spa
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): ... print(person) ... {'name': 'Mike', 'id': 4} {'name': 'Sandra', 'id': 2}
在Python中使用枚舉函數可讓Python將從數組中輸出的列表索引進行編號。筆者製做了一個包含三個元素的列表對這一功能進行展現:
l = [5,10,15]
如今能夠利用如下方法來訪問數組索引:
l[1] 10 l[0] 5 l[2] 15
在這些列表中進行枚舉時,維度的索引位置和維度會結合產生一個新的變量。請注意這一新變量的類型。
Python會自動將這些索引置入一個元組之中,這一點十分奇怪。筆者仍是傾向於從只有一個元素的Python庫中得到這些結果。還好,咱們能夠把這些枚舉函數置入到一個Python庫中。
data = dict(enumerate(l))
輸入以上代碼以後就會得出:
>>> data {0: 5, 1: 10, 2: 15}
Sort函數對於經常須要處理大量數據的人來講相當重要,它將字符串根據首字母A到B進行排列,將整數和倍數自負無窮起由小至大排列。須要注意的是,這一函數沒法用於帶有字符串和整數或浮點數的列表。
l = [15,6,1,8] for i in sorted(l): print(i) 1 6 8 15
也能夠將相反的參數設爲False來進行逆運算。
for i in sorted(l,reverse = True): print(i) 15 8 6 1
對於可用的最後一個參數,可使用key函數。Key是一個應用於已知循環中的每一個維度的函數。而筆者偏向於使用lambda,Lambda會創造一個匿名但仍可調用的函數。
l.sort(key=lambda s: s[::-1])
寫代碼時,遇到大量的帶有迭代的數據在所不免。簡潔成就卓越,這些方法可以使代碼簡潔明瞭而且運行起來更快。循環的世界值得你繼續探索!
文源網絡,僅供學習之用,侵刪。在學習Python的道路上確定會碰見困難,別慌,我這裏有一套學習資料,包含40+本電子書,800+個教學視頻,涉及Python基礎、爬蟲、框架、數據分析、機器學習等,不怕你學不會!
https://shimo.im/docs/JWCghr8... 《Python學習資料》關注公衆號【Python圈子】,優質文章每日送達。