Python 的 zip() 函式
zip() 函式用於對多個迭代器進行分組。使用 help 方法檢視 zip() 函式的文件。執行以下程式碼,獲取有關 zip() 函式的幫助。
示例
help(zip)
如果您執行以上程式,您會獲得以下結果。
輸出
Help on class zip in module builtins: class zip(object) | zip(iter1 [,iter2 [...]]) --> 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. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling.
我們來看一下一個簡單的示例,瞭解其工作原理?
示例
## initializing two lists names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## zipping both ## zip() will return pairs of tuples with corresponding elements from both lists print(list(zip(names, ages)))
如果您執行以上程式,您會獲得以下結果
輸出
[('Harry', 19), ('Emma', 20), ('John', 18)]
我們還可以從壓縮物件中解壓元素。我們必須傳遞一個物件並用一個前導 * 傳遞給 zip() 函式。我們來看一下。
示例
## initializing two lists names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## zipping both ## zip() will return pairs of tuples with corresponding elements from both lists zipped = list(zip(names, ages)) ## unzipping new_names, new_ages = zip(*zipped) ## checking new names and ages print(new_names) print(new_ages)
如果您執行以上程式,您會獲得以下結果。
('Harry', 'Emma', 'John') (19, 20, 18)
zip() 的一般用途
我們可以使用它來同時列印來自不同迭代器的多個對應元素。我們來看一下以下示例。
示例
## initializing two lists names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## printing names and ages correspondingly using zip() for name, age in zip(names, ages): print(f"{name}'s age is {age}")
如果您執行以上程式,您會獲得以下結果。
輸出
Harry's age is 19 Emma's age is 20 John's age is 18
廣告