Hướng dẫn python itertools

Python’s Itertool là một mô-đun cung cấp các chức năng khác nhau hoạt động trên các trình vòng lặp để tạo ra các trình vòng lặp phức tạp. Mô-đun này hoạt động như một công cụ nhanh, tiết kiệm bộ nhớ được sử dụng riêng lẻ hoặc kết hợp để tạo thành đại số trình lặp.

Ví dụ: giả sử có hai danh sách và bạn muốn nhân các phần tử của chúng. Có thể có một số cách để đạt được điều này. Người ta có thể sử dụng cách tiếp cận ngây thơ, tức là bằng cách lặp lại đồng thời các phần tử của cả hai danh sách và nhân chúng lên. Và một cách tiếp cận khác có thể là sử dụng hàm bản đồ, tức là bằng cách chuyển toán tử mul làm tham số đầu tiên cho hàm bản đồ và Lists làm tham số thứ hai và thứ ba cho hàm này. Hãy xem thời gian thực hiện của mỗi cách tiếp cận.

# Python program to demonstrate
# iterator module
 
 
import operator
import time
 
# Defining lists
L1 = [1, 2, 3]
L2 = [2, 3, 4]
 
# Starting time before map
# function
t1 = time.time()
 
# Calculating result
a, b, c = map(operator.mul, L1, L2)
 
# Ending time after map
# function
t2 = time.time()
 
# Time taken by map function
print("Result:", a, b, c)
print("Time taken by map function: %.6f" %(t2 - t1))
 
# Starting time before naive
# method
t1 = time.time()
 
# Calculating result using for loop
print("Result:", end = " ")
for i in range(3):
    print(L1[i] * L2[i], end = " ")
     
# Ending time after naive
# method
t2 = time.time()
print("\nTime taken by for loop: %.6f" %(t2 - t1))

output

Result: 2 6 12
Time taken by map function: 0.000005
Result: 2 6 12 
Time taken by for loop: 0.000014

Trong ví dụ trên, có thể thấy rằng thời gian thực hiện bởi hàm bản đồ xấp xỉ một nửa thời gian thực hiện bởi vòng lặp for. Điều này cho thấy itertools là công cụ nhanh, tiết kiệm bộ nhớ.

Các loại trình vòng lặp khác nhau được cung cấp bởi mô-đun này là:

  • Infinite iterators
  • Combinatoric iterators
  • Terminating iterators

  • 1. Infinite iterators
  • 2.Combinatoric iterators(trình vòng lặp tổ hợp)
  • 3.Terminating iterators

1. Infinite iterators

Trình lặp trong Python là bất kỳ kiểu Python nào có thể được sử dụng với ‘vòng lặp for trong’. Danh sách Python, bộ giá trị, từ điển và bộ đều là ví dụ về trình vòng lặp có sẵn. Nhưng không nhất thiết một đối tượng vòng lặp phải cạn kiệt, đôi khi nó có thể là vô hạn. Loại trình vòng lặp như vậy được gọi là trình vòng lặp vô hạn(Infinite iterators).

Python cung cấp ba loại trình lặp vô hạn:

count(start, step): Trình lặp này bắt đầu in từ số “bắt đầu” và in vô hạn. Nếu các bước được đề cập, các con số sẽ bị bỏ qua nếu bước khác là 1 theo mặc định. Xem ví dụ dưới đây để biết cách sử dụng với vòng lặp for in.

Thí dụ:

# Python program to demonstrate
# infinite iterators
   
import itertools
   
# for in loop
for i in itertools.count(5, 5):
    if i == 35:
        break
    else:
        print(i, end =" ")

output

5 10 15 20 25 30

cycle(iterable):: Trình lặp này in tất cả các giá trị theo thứ tự từ vùng chứa đã truyền. Nó khởi động lại quá trình in từ đầu một lần nữa khi tất cả các phần tử được in theo cách tuần hoàn.

Ví dụ 1:

# Python program to demonstrate
# infinite iterators
   
import itertools
   
count = 0
   
# for in loop
for i in itertools.cycle('AB'):
    if count > 7:
        break
    else:
        print(i, end = " ")
        count += 1

output

A B A B A B A B 
# Python program to demonstrate
# infinite iterators
   
import itertools
   
l = ['Cafe', 'dev', 'n']
   
# defining iterator
iterators = itertools.cycle(l)
   
# for in loop
for i in range(6):
       
    # Using next function
    print(next(iterators), end = " ")

output

Cafe dev n Cafe dev n 

repeat (val, num): Trình lặp này in lặp đi lặp lại giá trị đã truyền vô số lần. Nếu từ khóa tùy chọn num được đề cập, thì nó lặp lại số lần num.

# Python code to demonstrate the working of  
# repeat() 
     
# importing "itertools" for iterator operations 
import itertools 
     
# using repeat() to repeatedly print number 
print ("Printing the numbers repeatedly : ") 
print (list(itertools.repeat(25, 4)))

output

Printing the numbers repeatedly : 
[25, 25, 25, 25]

2.Combinatoric iterators(trình vòng lặp tổ hợp)

Các trình tạo đệ quy được sử dụng để đơn giản hóa các cấu trúc tổ hợp như hoán vị, tổ hợp và tích Đề-các được gọi là các biến lặp tổ hợp.

Trong Python có 4 trình vòng lặp tổ hợp:

Product(): Công cụ này tính toán sản phẩm theo cacte của các đầu vào lặp lại. Để tính toán sản phẩm của một tệp có thể lặp lại với chính nó, chúng tôi sử dụng đối số từ khóa lặp lại tùy chọn để chỉ định số lần lặp lại. Đầu ra của hàm này là các bộ giá trị theo thứ tự được sắp xếp.

Thí dụ

# import the product function from itertools module
from itertools import product
   
print("The cartesian product using repeat:")
print(list(product([1, 2], repeat = 2)))
print()
   
print("The cartesian product of the containers:")
print(list(product(['cafe', 'dev', 'n'], '2')))
print()
   
print("The cartesian product of the containers:")
print(list(product('AB', [3, 4])))

output

The cartesian product using repeat:
[(1, 1), (1, 2), (2, 1), (2, 2)]

The cartesian product of the containers:
[('cafe', '2'), ('dev', '2'), ('n', '2')]

The cartesian product of the containers:
[('A', 3), ('A', 4), ('B', 3), ('B', 4)]

Permutations(): Permutations() như tên gọi của chính nó được sử dụng để tạo ra tất cả các hoán vị có thể có của một biến có thể lặp lại. Tất cả các yếu tố được coi là duy nhất dựa trên vị trí của chúng chứ không phải giá trị của chúng. Hàm này nhận kích thước nhóm và kích thước nhóm có thể lặp lại, nếu giá trị của kích thước nhóm không được chỉ định hoặc bằng Không thì giá trị của kích thước nhóm sẽ trở thành độ dài của kích thước có thể lặp lại.

# import the product function from itertools module
from itertools import permutations
   
print ("All the permutations of the given list is:") 
print (list(permutations([1, 'cafedev'], 2)))
print()
  Terminating iterators
print ("All the permutations of the given string is:") 
print (list(permutations('AB')))
print()
   
print ("All the permutations of the given container is:") 
print(list(permutations(range(3), 2)))

output

All the permutations of the given list is:
[(1, 'cafedev'), ('cafedev', 1)]

All the permutations of the given string is:
[('A', 'B'), ('B', 'A')]

All the permutations of the given container is:
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]

Combinations(): Trình lặp này in tất cả các kết hợp có thể có (không thay thế) của vùng chứa được truyền vào các đối số trong kích thước nhóm được chỉ định theo thứ tự được sắp xếp.

# import combinations from itertools module
   
from itertools import combinations
   
print ("All the combination of list in sorted order(without replacement) is:") 
print(list(combinations(['A', 2], 2)))
print()
   
print ("All the combination of string in sorted order(without replacement) is:")
print(list(combinations('AB', 2)))
print()
   
print ("All the combination of list in sorted order(without replacement) is:")
print(list(combinations(range(2), 1)))

output

All the combination of list in sorted order(without replacement) is:
[('A', 2)]

All the combination of string in sorted order(without replacement) is:
[('A', 'B')]

All the combination of list in sorted order(without replacement) is:
[(0, ), (1, )]

Combination_with_replacement(): Hàm này trả về một dãy con có độ dài n từ các phần tử của có thể lặp trong đó n là đối số mà hàm lấy để xác định độ dài của các dãy con được tạo bởi hàm. Các phần tử riêng lẻ có thể tự lặp lại trong hàm links_with_replacement.

# import combinations from itertools module
   
from itertools import combinations_with_replacement
   
print ("All the combination of string in sorted order(with replacement) is:")
print(list(combinations_with_replacement("AB", 2)))
print()
   
print ("All the combination of list in sorted order(with replacement) is:")
print(list(combinations_with_replacement([1, 2], 2)))
print()
   
print ("All the combination of container in sorted order(with replacement) is:")
print(list(combinations_with_replacement(range(2), 1)))

output

All the combination of string in sorted order(with replacement) is:
[('A', 'A'), ('A', 'B'), ('B', 'B')]

All the combination of list in sorted order(with replacement) is:
[(1, 1), (1, 2), (2, 2)]

All the combination of container in sorted order(with replacement) is:
[(0, ), (1, )]Terminating iterators

3.Terminating iterators

Trình lặp kết thúc được sử dụng để làm việc trên các chuỗi đầu vào ngắn và tạo ra đầu ra dựa trên chức năng của phương thức được sử dụng.

Các loại trình lặp kết thúc khác nhau là:

accumulate(iter, func): Trình lặp này nhận hai đối số, mục tiêu có thể lặp lại và hàm sẽ được theo sau ở mỗi lần lặp giá trị trong mục tiêu. Nếu không có chức năng nào được chuyển, việc bổ sung diễn ra theo mặc định. Nếu đầu vào có thể lặp lại trống, đầu ra có thể lặp lại cũng sẽ trống.

# Python code to demonstrate the working of 
# accumulate()
 
 
import itertools
import operator
 
# initializing list 1
li1 = [1, 4, 5, 7]
   
# using accumulate()
# prints the successive summation of elements
print ("The sum after each iteration is : ", end ="")
print (list(itertools.accumulate(li1)))
   
# using accumulate()
# prints the successive multiplication of elements
print ("The product after each iteration is : ", end ="")
print (list(itertools.accumulate(li1, operator.mul)))
   
# using accumulate()
# prints the successive summation of elements
print ("The sum after each iteration is : ", end ="")
print (list(itertools.accumulate(li1)))
   
# using accumulate()
# prints the successive multiplication of elements
print ("The product after each iteration is : ", end ="")
print (list(itertools.accumulate(li1, operator.mul)))

output

The sum after each iteration is : [1, 5, 10, 17]
The product after each iteration is : [1, 4, 20, 140]
The sum after each iteration is : [1, 5, 10, 17]
The product after each iteration is : [1, 4, 20, 140]

chain (iter1, iter2 ..): Hàm này được sử dụng để in tất cả các giá trị trong các mục tiêu có thể lặp lại lần lượt được đề cập trong các đối số của nó.

# Python code to demonstrate the working of 
# and chain()
   
 
import itertools
 
# initializing list 1
li1 = [1, 4, 5, 7]
   
# initializing list 2
li2 = [1, 6, 5, 9]
   
# initializing list 3
li3 = [8, 10, 5, 4]
 
# using chain() to print all elements of lists
print ("All values in mentioned chain are : ", end ="")
print (list(itertools.chain(li1, li2, li3)))

output

All values in mentioned chain are : [1, 4, 5, 7, 1, 6, 5, 9, 8, 10, 5, 4]

chain.from_iterable(): Hàm này được triển khai tương tự như chain () nhưng đối số ở đây là danh sách các danh sách hoặc bất kỳ vùng chứa có thể lặp lại nào khác.

# Python code to demonstrate the working of 
# chain.from_iterable()
 
 
import itertools
 
 
# initializing list 1
li1 = [1, 4, 5, 7]
   
# initializing list 2
li2 = [1, 6, 5, 9]
   
# initializing list 3
li3 = [8, 10, 5, 4]
   
# initializing list of list
li4 = [li1, li2, li3]
 
# using chain.from_iterable() to print all elements of lists
print ("All values in mentioned chain are : ", end ="")
print (list(itertools.chain.from_iterable(li4)))

ouput

All values in mentioned chain are : [1, 4, 5, 7, 1, 6, 5, 9, 8, 10, 5, 4]

compress(iter, selector): Trình lặp này chọn lọc các giá trị cần in từ vùng chứa đã truyền theo giá trị danh sách boolean được truyền như các đối số khác. Các đối số tương ứng với boolean true được in ra nếu không tất cả đều bị bỏ qua.

Thí dụ:

# Python code to demonstrate the working of 
# and compress()
 
 
import itertools
 
 
# using compress() selectively print data values
print ("The compressed values in string are : ", end ="")
print (list(itertools.compress('CAFEDEVN', [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0])))

output

The compressed values in string are : ['C', 'F', 'N']

drop while (func, seq): Trình lặp này bắt đầu in các ký tự chỉ sau func. trong đối số trả về false lần đầu tiên.

# Python code to demonstrate the working of 
# dropwhile()
 
 
import itertools
 
 
# initializing list 
li = [2, 4, 5, 7, 8]
   
# using dropwhile() to start displaying after condition is false
print ("The values after condition returns false : ", end ="")
print (list(itertools.dropwhile(lambda x : x % 2 == 0, li)))

output

The values after condition returns false : [5, 7, 8]

filterfalse (func, seq): Như tên cho thấy, trình lặp này chỉ in các giá trị trả về false cho hàm đã truyền.

Thí dụ:

# Python code to demonstrate the working of 
# filterfalse()
   
 
import itertools
   
# initializing list 
li = [2, 4, 5, 7, 8]
 
# using filterfalse() to print false values
print ("The values that return false to function are : ", end ="")
print (list(itertools.filterfalse(lambda x : x % 2 == 0, li)))

output

The values that return false to function are : [5, 7]

islice(iterable, start, stop, step): Trình lặp này in chọn lọc các giá trị được đề cập trong vùng chứa có thể lặp lại của nó được truyền dưới dạng đối số. Trình lặp này nhận 4 đối số, vùng chứa có thể lặp lại, vị trí bắt đầu, vị trí kết thúc và bước.

Thí dụ:

# Python code to demonstrate the working of 
# islice()
   
  
import itertools
   
# initializing list 
li = [2, 4, 5, 7, 8, 10, 20]
     
# using islice() to slice the list acc. to need
# starts printing from 2nd index till 6th skipping 2
print ("The sliced list values are : ", end ="")
print (list(itertools.islice(li, 1, 6, 2)))

ouput

The sliced list values are : [4, 7, 10]

starmap (func., tuple list): Trình vòng lặp này nhận một hàm và danh sách tuple làm đối số và trả về giá trị theo hàm từ mỗi bộ danh sách.

# Python code to demonstrate the working of 
# starmap()
   
 
import itertools
   
   
# initializing tuple list
li = [ (1, 10, 5), (8, 4, 1), (5, 4, 9), (11, 10, 1) ]
   
# using starmap() for selection value acc. to function
# selects min of all tuple values
print ("The values acc. to function are : ", end ="")
print (list(itertools.starmap(min, li)))

ouput

The values acc. to function are : [1, 1, 4, 1]

take while (func, iterable): Trình lặp này ngược lại với dropworthy (), nó in các giá trị cho đến khi hàm trả về false lần đầu tiên.

Thí dụ:

# Python code to demonstrate the working of 
# takewhile()
   
 
import itertools
   
# initializing list 
li = [2, 4, 6, 7, 8, 10, 20]
   
# using takewhile() to print values till condition is false.
print ("The list values till 1st false value are : ", end ="")
print (list(itertools.takewhile(lambda x : x % 2 == 0, li )))

ouput

The list values till 1st false value are : [2, 4, 6]

tee(iterator, count): – Trình vòng lặp này chia vùng chứa thành một số trình vòng lặp được đề cập trong đối số.

Thí dụ:

# Python code to demonstrate the working of 
# tee()
   
 
import itertools
   
# initializing list 
li = [2, 4, 6, 7, 8, 10, 20]
   
# storing list in iterator
iti = iter(li) 
   
# using tee() to make a list of iterators
# makes list of 3 iterators having same values.
it = itertools.tee(iti, 3)
   
# printing the values of iterators
print ("The iterators are : ")
for i in range (0, 3):
    print (list(it[i]))

output

The iterators are : 
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]
[2, 4, 6, 7, 8, 10, 20]

zip_longest (iterable1, iterable2, fillval): Trình lặp này in các giá trị của các vòng lặp theo thứ tự. Nếu một trong các tệp lặp được in đầy đủ, các giá trị còn lại được lấp đầy bởi các giá trị được gán cho giá trị điền.

Thí dụ:

# Python code to demonstrate the working of 
# zip_longest()
   
 
import itertools
   
# using zip_longest() to combine two iterables.
print ("The combined values of iterables is  : ")
print (*(itertools.zip_longest('GesoGes', 'ekfrek', fillvalue ='_' )))

output

The combined values of iterables is  : 
('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')

Cài ứng dụng cafedev để dễ dàng cập nhật tin và học lập trình mọi lúc mọi nơi tại đây.

Nguồn và Tài liệu tiếng anh tham khảo:

  • python.org

Tài liệu từ cafedev:

  • Full series tự học Python từ cơ bản tới nâng cao tại đây nha.
  • Tự học ML bằng Python từ cơ bản tới nâng cao.
  • Các nguồn kiến thức MIỄN PHÍ VÔ GIÁ từ cafedev tại đây

Nếu bạn thấy hay và hữu ích, bạn có thể tham gia các kênh sau của cafedev để nhận được nhiều hơn nữa:

  • Group Facebook
  • Fanpage
  • Youtube
  • Instagram
  • Twitter
  • Linkedin
  • Pinterest
  • Trang chủ

Chào thân ái và quyết thắng!

Đăng ký kênh youtube để ủng hộ Cafedev nha các bạn, Thanks you!