zip() ฟังก์ชันนี้ใช้สำหรับจับกลุ่ม iterator หลายตัว มาดูเอกสารของฟังก์ชัน zip() โดยใช้เมธอด help รันโค้ดต่อไปนี้เพื่อดูความช่วยเหลือเกี่ยวกับฟังก์ชัน 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.
มาดูตัวอย่างง่ายๆ ว่ามันทำงานอย่างไร
ตัวอย่าง
## เริ่มต้นสอง List names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## zip ทั้งสอง ## zip() จะคืนคู่ของ tuples พร้อมองค์ประกอบที่สอดคล้องจากทั้งสอง List print(list(zip(names, ages)))
หากรันโปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังนี้
ผลลัพธ์
[('Harry', 19), ('Emma', 20), ('John', 18)]
เราสามารถ unzip องค์ประกอบจาก zipped object ได้ เราต้องส่ง object พร้อม * นำหน้าให้ฟังก์ชัน zip() มาดู
ตัวอย่าง
## เริ่มต้นสอง List names = ['Harry', 'Emma', 'John'] ages = [19, 20, 18] ## zip ทั้งสอง ## zip() จะคืนคู่ของ tuples พร้อมองค์ประกอบที่สอดคล้องจากทั้งสอง List zipped = list(zip(names, ages)) ## unzip new_names, new_ages = zip(*zipped) ## ตรวจสอบ names และ ages ใหม่ print(new_names) print(new_ages)
หากรันโปรแกรมข้างต้น คุณจะได้ผลลัพธ์ดังนี้
('Harry', 'Emma', 'John')
(19, 20, 18)
การใช้งาน zip() ทั่วไป
เราสามารถใช้มันเพื่อพิมพ์องค์ประกอบที่สอดคล้องจาก iterator ต่างๆ หลายตัวพร้อมกัน มาดูตัวอย่างต่อไปนี้
ตัวอย่าง
## เริ่มต้นสอง List
names = ['Harry', 'Emma', 'John']
ages = [19, 20, 18]
## พิมพ์ names และ ages ที่สอดคล้องกันโดยใช้ 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