您的位置:首頁技術文章
文章詳情頁

Python同時迭代多個序列的方法

瀏覽:41日期:2022-07-16 10:34:59

問題

你想同時迭代多個序列,每次分別從一個序列中取一個元素。

解決方案

為了同時迭代多個序列,使用 zip() 函數。比如:

>>> xpts = [1, 5, 4, 2, 10, 7]>>> ypts = [101, 78, 37, 15, 62, 99]>>> for x, y in zip(xpts, ypts):... print(x,y)...1 1015 784 372 1510 627 99>>>

zip(a, b) 會生成一個可返回元組 (x, y) 的迭代器,其中x來自a,y來自b。一旦其中某個序列到底結尾,迭代宣告結束。因此迭代長度跟參數中最短序列長度一致。

>>> a = [1, 2, 3]>>> b = [’w’, ’x’, ’y’, ’z’]>>> for i in zip(a,b):... print(i)...(1, ’w’)(2, ’x’)(3, ’y’)>>>

如果這個不是你想要的效果,那么還可以使用 itertools.zip_longest() 函數來代替。比如:

>>> from itertools import zip_longest>>> for i in zip_longest(a,b):... print(i)...(1, ’w’)(2, ’x’)(3, ’y’)(None, ’z’)

>>> for i in zip_longest(a, b, fillvalue=0):... print(i)...(1, ’w’)(2, ’x’)(3, ’y’)(0, ’z’)>>>

討論

當你想成對處理數據的時候 zip() 函數是很有用的。比如,假設你頭列表和一個值列表,就像下面這樣:

headers = [’name’, ’shares’, ’price’]values = [’ACME’, 100, 490.1]

使用zip()可以讓你將它們打包并生成一個字典:

s = dict(zip(headers,values))

或者你也可以像下面這樣產生輸出:

for name, val in zip(headers, values): print(name, ’=’, val)

雖然不常見,但是 zip() 可以接受多于兩個的序列的參數。這時候所生成的結果元組中元素個數跟輸入序列個數一樣。比如;

>>> a = [1, 2, 3]>>> b = [10, 11, 12]>>> c = [’x’,’y’,’z’]>>> for i in zip(a, b, c):... print(i)...(1, 10, ’x’)(2, 11, ’y’)(3, 12, ’z’)>>>

最后強調一點就是,zip() 會創建一個迭代器來作為結果返回。如果你需要將結對的值存儲在列表中,要使用 list() 函數。比如:

>>> zip(a, b)<zip object at 0x1007001b8>>>> list(zip(a, b))[(1, 10), (2, 11), (3, 12)]>>>

以上就是Python同時迭代多個序列的方法的詳細內容,更多關于Python同時迭代多個序列的資料請關注好吧啦網其它相關文章!

標簽: Python 編程
相關文章:
国产综合久久一区二区三区