Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the itertools package of python

Shulou Source: shulou.com Published: 2022-06-01 06:42:39 10月04日 Update

This article mainly introduces the python itertools package how to use the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this python itertools package how to use the article will have a harvest, let's take a look.

Foreword:

Python's built-in module itertools provides very useful functions for manipulating iterative objects, and several "infinite" iterators provided by itertools

1. Count () creates a sequence of natural numbers import itertools n = 0natuals = itertools.count (1) for m in natuals: print (m)

Because count (n) creates an infinite iterator, starting with n, iterating to infinity. So the above code will print out a sequence of natural numbers, can not stop at all, can only press Ctrl+C to exit.

Running result:

0 1 2 3 4 5 6 7...

2. Cycle () creates a sequence loop

Cycle () repeats an incoming sequence indefinitely.

Example 1. The contents of the circular list:

Natuals = itertools.cycle ([1,2,3]) for m in natuals: print (m)

Running result:

1 2 3 1 2 3 1 2 3...

Example 2. Character loop in a string:

Import itertoolscs = itertools.cycle ('ABC') # Note that a string is also a for c in cs of a sequence: print (c)

Running result:

A B C A B C A B C...

3. Repeat () repeats an element a finite number of times

Repeat () is responsible for repeating an element indefinitely (the default behavior), but you can limit the number of repeats if you provide a second parameter.

Ns = itertools.repeat ('Aids, 3) for n in ns: print (n)

Running result:

An An A...

4. Takewhile () intercepts a finite sequence according to conditional judgment.

An infinite sequence iterates indefinitely only when for iterates. If you just create an iterative object, it does not generate infinite elements in advance, and in fact it is impossible to create unlimited elements in memory. Although the infinite sequence can be iterated indefinitely, we usually intercept a finite sequence according to the conditional judgment through functions such as takewhile ().

Import itertools natuals = itertools.count (1) ns = itertools.takewhile (lambda x: X

Tags: Iterations elements sequences results runs functions characters objects content strings finite knowledge loops two data more conditions examples articles nature Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno NVidia Apple Redmi vpn