5個小技巧,讓你的for循環(huán)瞬間高大上!
本文轉(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ù)。
- for first,second in zip(array1,array2):
- print(first)
- print(second)
在一個偶整數(shù)序列和一個奇整數(shù)序列中使用這一方法就能體現(xiàn)出這一函數(shù)的功效。
- odds = [1,3,5,7,9]
- evens = [2,4,6,8,10]
- for oddnum, evennum in zip(odds,evens):
- print(oddnum)
- print(evennum)
以上函數(shù)輸出的結(jié)果便是:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
In Range函數(shù):編寫C-Style循環(huán)
C-Style似乎看起來有點兒平凡,但它能在循環(huán)中煥發(fā)光彩。
- for i in range(10):
- print(i)
- if i == 3:
- i.update(7)
C語言愛好者可能覺得以上的代碼并不是C-Style循環(huán),但如果不想自己動手編寫迭代函數(shù),以上內(nèi)容已經(jīng)是最完美的形式了。
不過筆者熱衷于“浪費時間”,因此決定編寫一個新的迭代程序來寫出盡可能完美的C-Style循環(huán)。
- 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()函數(shù):只對需要的數(shù)據(jù)進行循環(huán)
在處理大量的數(shù)據(jù)時,使用filter函數(shù)能夠使得數(shù)據(jù)在使用時效果更佳。Filter函數(shù)正如其名,其功效是在對數(shù)據(jù)進行迭代前進行過濾。當(dāng)只需要使用某一范圍內(nèi)的數(shù)據(jù)而且不想再添加一個條件時,filter十分實用。
- 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}
Enumerate()函數(shù):對維度進行索引
在Python中使用枚舉函數(shù)可以讓Python將從數(shù)組中輸出的列表索引進行編號。筆者制作了一個包含三個元素的列表對這一功能進行展示:
- l = [5,10,15]
現(xiàn)在可以利用以下方法來訪問數(shù)組索引:
- l[1]
- 10
- l[0]
- 5
- l[2]
- 15
在這些列表中進行枚舉時,維度的索引位置和維度會結(jié)合產(chǎn)生一個新的變量。請注意這一新變量的類型。
Python會自動將這些索引置入一個元組之中,這一點十分奇怪。筆者還是傾向于從只有一個元素的Python庫中獲得這些結(jié)果。還好,我們可以把這些枚舉函數(shù)置入到一個Python庫中。
- data = dict(enumerate(l))
輸入以上代碼之后就會得出:
- >>> data
- {0: 5, 1: 10, 2: 15}
圖源:unsplash
Sorted()函數(shù):使用數(shù)據(jù)中進行排序,而非使用前
Sort函數(shù)對于常常需要處理大量數(shù)據(jù)的人來說至關(guān)重要,它將字符串根據(jù)首字母A到B進行排列,將整數(shù)和倍數(shù)自負無窮起由小至大排列。需要注意的是,這一函數(shù)無法用于帶有字符串和整數(shù)或浮點數(shù)的列表。
- l = [15,6,1,8]
- for i in sorted(l):
- print(i)
- 1
- 6
- 8
- 15
也可以將相反的參數(shù)設(shè)為False來進行逆運算。
- for i in sorted(l,reverse = True):
- print(i)
- 15
- 8
- 6
- 1
對于可用的最后一個參數(shù),可以使用key函數(shù)。Key是一個應(yīng)用于已知循環(huán)中的每個維度的函數(shù)。而筆者偏向于使用lambda,Lambda會創(chuàng)造一個匿名但仍可調(diào)用的函數(shù)。
- l.sort(key=lambda s: s[::-1])
寫代碼時,遇到大量的帶有迭代的數(shù)據(jù)在所難免。簡潔成就卓越,這些方法能夠使代碼簡潔明了并且運行起來更快。循環(huán)的世界值得你繼續(xù)探索!