python3.x?zip用法小結(jié)
1.zip用法簡(jiǎn)介
在python 3.x系列中,zip方法返回的為一個(gè)zip object可迭代對(duì)象。
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ò)上面的注釋,不難看出該迭代器的兩個(gè)關(guān)鍵點(diǎn):
1.迭代器的next方法返回一個(gè)元組,元組的第i個(gè)元素為各個(gè)輸入?yún)?shù)的第i個(gè)元素。
2.迭代器的next方法,遇到輸入序列中最短的那個(gè)序列迭代完畢,則會(huì)停止運(yùn)行。
為了看清楚zip的效果,我們先看個(gè)最簡(jiǎn)單的例子
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方法返回的,是一個(gè)zip對(duì)象。
zip對(duì)象是個(gè)迭代器,用next方法即可對(duì)其完成遍歷。
當(dāng)然我們也可以用for循環(huán)完成對(duì)zip對(duì)象的遍歷。
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ù)不等長(zhǎng)進(jìn)行截?cái)?/h2>
zip方法中,如果傳入的參數(shù)不等長(zhǎng),則會(huì)進(jìn)行截?cái)啵財(cái)嗟臅r(shí)候會(huì)取最短的那個(gè)序列,超過(guò)最短序列長(zhǎng)度的其他序列元素,則會(huì)被舍棄掉。
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
上述的方法如果運(yùn)行,結(jié)果為
('a', '1')
('b', '2')
('c', '3')
('d', '4')
3.python3.x 與2.x中zip的不同
python3.x中,zip方法返回的是一個(gè)zip對(duì)象,本質(zhì)是一個(gè)迭代器。而在python2.x中,zip方法直接返回一個(gè)list。
返回迭代器的好處在于,可以節(jié)省list占用的內(nèi)存,只在有需要的時(shí)候再調(diào)用相關(guān)數(shù)據(jù)。
4.用zip方法構(gòu)建字典
zip方法在實(shí)際中用途非常廣泛,我們下面可以看幾個(gè)實(shí)際中常用的例子。
zip方法可以用來(lái)構(gòu)建字典。
字典包含兩部分?jǐn)?shù)據(jù):key列表與value列表。如果我們現(xiàn)在有key序列與value序列,用zip方法可以很快構(gòu)建一個(gè)字典。
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.對(duì)多個(gè)序列的元素進(jìn)行排序
排序也是日常工作中的常見需求,對(duì)多個(gè)序列進(jìn)行排序而不破壞其元素的相對(duì)關(guān)系,也非常常見。下面我們來(lái)看一個(gè)常見的案例
還是以之前的數(shù)據(jù)為例
有names序列與scores序列,我們希望按照names進(jìn)行排序,同時(shí)保持對(duì)應(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)]
如果我們希望按照分?jǐn)?shù)逆序排,則可以按如下代碼運(yùn)行
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.對(duì)多組數(shù)據(jù)進(jìn)行計(jì)算
假設(shè)我們有3個(gè)序列,sales,costs,allowances。其中利潤(rùn)為銷售額-成本+補(bǔ)貼,現(xiàn)在我們想求每組利潤(rù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
當(dāng)然我們也可以使用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方法比f(wàn)or循環(huán)還是要更直觀,更簡(jiǎn)潔,更優(yōu)雅。
7.*操作符進(jìn)行解壓
我們還可以使用*操作符對(duì)zip對(duì)象進(jìn)行解壓,效果是將zip object還原至原來(lái)的對(duì)象,效果就類似于壓縮以后得解壓。
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)
上面代碼運(yùn)行的結(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python讀取測(cè)試數(shù)據(jù)的多種方式
本文主要介紹了python讀取測(cè)試數(shù)據(jù)的多種方式,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08python wav模塊獲取采樣率 采樣點(diǎn)聲道量化位數(shù)(實(shí)例代碼)
這篇文章主要介紹了python wav模塊獲取采樣率 采樣點(diǎn)聲道量化位數(shù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01Pycharm開發(fā)Django項(xiàng)目創(chuàng)建ORM模型的問題
ORM,全稱Object Relational Mapping,通過(guò)ORM我們可以通過(guò)類的方式去操作數(shù)據(jù)庫(kù),而不用再寫原生的SQL語(yǔ)句,下面通過(guò)本文給大家介紹Pycharm開發(fā)Django項(xiàng)目ORM模型介紹,感興趣的朋友一起看看吧2021-10-10Pytorch 如何實(shí)現(xiàn)LSTM時(shí)間序列預(yù)測(cè)
本文主要基于Pytorch深度學(xué)習(xí)框架,實(shí)現(xiàn)LSTM神經(jīng)網(wǎng)絡(luò)模型,用于時(shí)間序列的預(yù)測(cè)2021-05-05基于Python實(shí)現(xiàn)簡(jiǎn)單的定時(shí)器詳解
所謂定時(shí)器,是指間隔特定時(shí)間執(zhí)行特定任務(wù)的機(jī)制。幾乎所有的編程語(yǔ)言,都有定時(shí)器的實(shí)現(xiàn)。這篇文章主要介紹的是通過(guò)Python實(shí)現(xiàn)的定時(shí)器,感興趣的可以跟隨小編學(xué)習(xí)一下2021-12-12Python time庫(kù)的時(shí)間時(shí)鐘處理
這篇文章主要介紹了Python time庫(kù)的時(shí)間時(shí)鐘處理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05詳解如何修改jupyter notebook的默認(rèn)目錄和默認(rèn)瀏覽器
這篇文章主要介紹了詳解如何修改jupyter notebook的默認(rèn)目錄和默認(rèn)瀏覽器,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01