Python looper - itertools

I. Introduction

Python's built-in modules itertoolsprovide very useful functional methods for manipulating iterables, such as infinite loops in 1 and 2, and Cartesian product loops that combine two lists.


2. Examples

1. Repeat the elements in the list cycle-cycle

The following code will repeat 1,2,3 for infinite printing:

from itertools import *

for i in cycle([1,2,3]):
    print(i)

output result


1
2
3
1
2
...

2. Accumulation loop -count

The following code will start at 10 and print infinitely every time it increases by 1.5:

from itertools import *

for i in count(10,1.5):
    print(i)

output result


10
11.5
13.0
...

3. Repeat loop -repeat

The following code prints 10 infinitely:

from itertools import *

for i in repeat(10):
    print(i)

output result


10
10
10
...

You can also specify the number of loops, such as specifying 5 loops:

from itertools import *

for i in repeat(10,5):
    print(i)

3. Summary

In addition to the above examples, there are many methods for us to use, you can directly visit the official documentation: https://docs.python.org/zh-cn/3/library/itertools.html for learning:
insert image description here


I recently read the official Python documentation: https://docs.python.org/zh-cn/3/contents.html and found a lot of skills that I didn’t know before. You can also go to the official documentation to supplement it, and there will be many reward.


Note: Remember to select the documentation for the corresponding version of python in your environment:
insert image description here


Guess you like

Origin blog.csdn.net/momoda118/article/details/121997209