Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report