Computer >> Máy Tính >  >> Lập trình >> Python

Hàm zip () trong Python

zip () hàm được sử dụng để nhóm nhiều trình vòng lặp. Xem tài liệu của zip () chức năng sử dụng trợ giúp phương pháp. Chạy mã sau để nhận trợ giúp về zip () chức năng.

Ví dụ

help(zip)

Nếu bạn chạy chương trình trên, bạn sẽ nhận được kết quả sau.

Đầu ra

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.

Hãy xem một ví dụ đơn giản về cách nó hoạt động?

Ví dụ

## 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)))

Nếu bạn chạy chương trình trên, bạn sẽ nhận được kết quả sau

Đầu ra

[('Harry', 19), ('Emma', 20), ('John', 18)]

Chúng ta cũng có thể giải nén các phần tử khỏi đối tượng đã nén. Chúng ta phải chuyển đối tượng có dấu * đứng trước vào zip () hàm số. Hãy xem.

Ví dụ

## 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)

Nếu bạn chạy chương trình trên, bạn sẽ nhận được kết quả sau.

('Harry', 'Emma', 'John')
(19, 20, 18)

Cách sử dụng chung của zip ()

Chúng ta có thể sử dụng nó để in nhiều phần tử tương ứng từ các trình vòng lặp khác nhau cùng một lúc. Hãy xem ví dụ sau.

Ví dụ

## 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}")

Nếu bạn chạy chương trình trên, bạn sẽ nhận được kết quả sau.

Đầu ra

Harry's age is 19
Emma's age is 20
John's age is 18