Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use a for loop to achieve an infinite loop effect

Shulou Source: shulou.com Published: 2022-06-02 10:23:49 10月25日 Update

This article will explain in detail how to use for loop to achieve an infinite loop effect, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

An infinite loop, also known as an endless loop, can be easily implemented with while True, so can a for loop achieve a similar function? Of course, with the help of the cycle function of the itertools module

Import time

From itertools import cycle

Cycle_iter = cycle ([100200,300])

For item in cycle_iter:

Print (item)

Time.sleep (1)

The for loop will go on and output 100,200,300. Is the function cycle () just for infinite loops? Of course not, it provides a way to loop through, and the following example shows you the practical application of this function

Lst1 = ['red',' blue', 'white']

Lst2 = ['Aids,' bundles, 'canals,' dudes, 'eaters,' Fathers,'G']

Here are two lists, which now require you to splice the elements in the two lists, one-to-one in order, and the final result is as follows

Red_A, blue_B, white_C, red_D, blue_E, white_F, red_G

It's a bit of a hassle to implement this function if you use the normal method, but it's very easy to use cycle ()

From itertools import cycle

Lst1 = ['red',' blue', 'white']

Lst2 = ['Aids,' bundles, 'canals,' dudes, 'eaters,' Fathers,'G']

Lst = []

Color_cycle = cycle (['red',' blue', 'white'])

For item in lst2:

Color = next (color_cycle)

Lst.append ('{color} _ {char} '.format (color=color, char=item))

Print (lst)

On how to use for loop to achieve an infinite loop effect is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Tags: Loops functions effects two content functions articles methods more knowledge articles good ordinary one-to-one elements actual modules examples results quality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi Shulou Information Microsoft MariaDB