python3.x?zip用法小結(jié)
1.zip用法簡介
在python 3.x系列中,zip方法返回的為一個zip object可迭代對象。
class zip(object): ? ? """ ? ? zip(*iterables) --> zip object ? ?? ? ? Return a zip object whose .__next__() method returns a tuple where ? ? the i-th element comes from the i-th iterable argument. ?The .__next__() ? ? method continues until the shortest iterable in the argument sequence ? ? is exhausted and then it raises StopIteration. ? ? """
通過上面的注釋,不難看出該迭代器的兩個關(guān)鍵點:
1.迭代器的next方法返回一個元組,元組的第i個元素為各個輸入?yún)?shù)的第i個元素。
2.迭代器的next方法,遇到輸入序列中最短的那個序列迭代完畢,則會停止運行。
為了看清楚zip的效果,我們先看個最簡單的例子
def fun0(): ? ? a = ['a', 'b', 'c', 'd'] ? ? b = ['1', '2', '3', '4'] ? ? result = zip(a, b) ? ? print(type(result)) ? ? try: ? ? ? ? while True: ? ? ? ? ? ? print(next(result)) ? ? except StopIteration: ? ? ? ? pass
上面的代碼,輸出結(jié)果為
<class 'zip'>
('a', '1')
('b', '2')
('c', '3')
('d', '4')
首先可以看到的是,zip方法返回的,是一個zip對象。
zip對象是個迭代器,用next方法即可對其完成遍歷。
當然我們也可以用for循環(huán)完成對zip對象的遍歷。
def fun00(): ? ? a = ['a', 'b', 'c', 'd'] ? ? b = ['1', '2', '3', '4'] ? ? result = zip(a, b) ? ? for ele in result: ? ? ? ? print(ele)
('a', '1')
('b', '2')
('c', '3')
('d', '4')
2.參數(shù)不等長進行截斷
zip方法中,如果傳入的參數(shù)不等長,則會進行截斷,截斷的時候會取最短的那個序列,超過最短序列長度的其他序列元素,則會被舍棄掉。
def fun0(): ? ? a = ['a', 'b', 'c', 'd'] ? ? b = ['1', '2', '3', '4', '5', '6'] ? ? result = zip(a, b) ? ? try: ? ? ? ? while True: ? ? ? ? ? ? print(next(result)) ? ? except StopIteration: ? ? ? ? pass
上述的方法如果運行,結(jié)果為
('a', '1')
('b', '2')
('c', '3')
('d', '4')
3.python3.x 與2.x中zip的不同
python3.x中,zip方法返回的是一個zip對象,本質(zhì)是一個迭代器。而在python2.x中,zip方法直接返回一個list。
返回迭代器的好處在于,可以節(jié)省list占用的內(nèi)存,只在有需要的時候再調(diào)用相關(guān)數(shù)據(jù)。
4.用zip方法構(gòu)建字典
zip方法在實際中用途非常廣泛,我們下面可以看幾個實際中常用的例子。
zip方法可以用來構(gòu)建字典。
字典包含兩部分數(shù)據(jù):key列表與value列表。如果我們現(xiàn)在有key序列與value序列,用zip方法可以很快構(gòu)建一個字典。
def fun5(): ? ? names = ['lili', 'lucy', 'tracy', 'larry'] ? ? scores = [98, 10, 75, 90] ? ? my_dict = dict(zip(names, scores)) ? ? print(my_dict)
{'lili': 98, 'lucy': 10, 'tracy': 75, 'larry': 90}
5.對多個序列的元素進行排序
排序也是日常工作中的常見需求,對多個序列進行排序而不破壞其元素的相對關(guān)系,也非常常見。下面我們來看一個常見的案例
還是以之前的數(shù)據(jù)為例
有names序列與scores序列,我們希望按照names進行排序,同時保持對應(yīng)的scores數(shù)據(jù)。
def fun3(): ? ? names = ['lili', 'lucy', 'tracy', 'larry'] ? ? scores = [98, 10, 75, 90] ? ? data = sorted(list(zip(names, scores)), key=lambda x: x[0], reverse=False) ? ? print(data)
輸出的結(jié)果為
[('larry', 90), ('lili', 98), ('lucy', 10), ('tracy', 75)]
如果我們希望按照分數(shù)逆序排,則可以按如下代碼運行
def fun3(): ? ? names = ['lili', 'lucy', 'tracy', 'larry'] ? ? scores = [98, 10, 75, 90] ? ? data = sorted(list(zip(names, scores)), key=lambda x: x[1], reverse=True) ? ? print(data)
[('lili', 98), ('larry', 90), ('tracy', 75), ('lucy', 10)]
6.對多組數(shù)據(jù)進行計算
假設(shè)我們有3個序列,sales,costs,allowances。其中利潤為銷售額-成本+補貼,現(xiàn)在我們想求每組利潤,就可以使用zip方法。
def fun4(): ? ? sales = [10000, 9500, 9000] ? ? costs = [9000, 8000, 7000] ? ? allowances = [200, 100, 150] ? ? for sale, cost, allowance in zip(sales, costs, allowances): ? ? ? ? profit = sale - cost + allowance ? ? ? ? print(f"profit is: {profit}")
profit is: 1200
profit is: 1600
profit is: 2150
當然我們也可以使用for循環(huán)
def fun4(): ? ? sales = [10000, 9500, 9000] ? ? costs = [9000, 8000, 7000] ? ? allowances = [200, 100, 150] ? ? for sale, cost, allowance in zip(sales, costs, allowances): ? ? ? ? profit = sale - cost + allowance ? ? ? ? print(f"profit is: {profit}")
? ? for i in range(len(sales)): ? ? ? ? profit = sales[i] - costs[i] + allowances[i] ? ? ? ? print(f"profit is: {profit}")
很明顯zip方法比for循環(huán)還是要更直觀,更簡潔,更優(yōu)雅。
7.*操作符進行解壓
我們還可以使用*操作符對zip對象進行解壓,效果是將zip object還原至原來的對象,效果就類似于壓縮以后得解壓。
def fun(): ? ? a = ['a', 'b', 'c', 'd'] ? ? b = ['1', '2', '3', '4'] ? ? result = list(zip(a, b)) ? ? print(result) ? ? zipobj = zip(a, b) ? ? a1, a2 = zip(*zipobj) ? ? print(list(a1)) ? ? print(a2)
上面代碼運行的結(jié)果為
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
['a', 'b', 'c', 'd']
('1', '2', '3', '4')
到此這篇關(guān)于python3.x zip用法詳解的文章就介紹到這了,更多相關(guān)python3 使用 zip內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python wav模塊獲取采樣率 采樣點聲道量化位數(shù)(實例代碼)
這篇文章主要介紹了python wav模塊獲取采樣率 采樣點聲道量化位數(shù),本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-01-01Pycharm開發(fā)Django項目創(chuàng)建ORM模型的問題
ORM,全稱Object Relational Mapping,通過ORM我們可以通過類的方式去操作數(shù)據(jù)庫,而不用再寫原生的SQL語句,下面通過本文給大家介紹Pycharm開發(fā)Django項目ORM模型介紹,感興趣的朋友一起看看吧2021-10-10Pytorch 如何實現(xiàn)LSTM時間序列預(yù)測
本文主要基于Pytorch深度學(xué)習(xí)框架,實現(xiàn)LSTM神經(jīng)網(wǎng)絡(luò)模型,用于時間序列的預(yù)測2021-05-05詳解如何修改jupyter notebook的默認目錄和默認瀏覽器
這篇文章主要介紹了詳解如何修改jupyter notebook的默認目錄和默認瀏覽器,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01