In some problems involving “cycles” (such as looping playback or polling tasks), it is necessary to iterate over a given list multiple times. Here, iteration means going from the first element to the last, and then starting again from the first element, repeating this process.
Let’s start with some music~
The following example will cyclically generate three colors, controlled by the range limit, showcasing the exciting combination of zip, range, and cycle!
from itertools import cycle
colors = ['red', 'green', 'blue']
for i, color in zip(range(5), cycle(colors)):
print(color) # Output: red, green, blue, red, green
As the song ends, today’s learning also comes to a close~If you plan to systematically and deeply learn Python, I highly recommend this book: “Python Programming from Beginner to Practice” (this textbook has sold over 500,000 copies and is very popular).
-
Beginner-friendly:Comprehensively covers the core syntax and programming thinking of Python (with very detailed accompanying code).
- Practical-oriented:Includes three complete project cases in game development, data visualization, and web applications.
Alternatively, you can check out the “Three Musketeers of Python Programming”. In addition to the above book, it includes the second book – Automating Tedious Tasks (Excel/PDF file processing/image editing/scheduled emails, etc.), and the third book – Geek Project Programming (image processing/3D rendering/machine learning, etc.).Recommended Reading
-
Lambda Functions and Sort for Dazzling Sorting
- Basic Algorithms in Python Programming – Lambda Functions and Sort Custom Sorting
- Prime Number Determination (Square Root Complexity)
- Basic Algorithms in Python Programming – Prime Number Determination
-
Python Programming Tips – Implementing Nested Loops with Product
-
Python Programming Tips – Implementing Nested Loops with Product
-
Zip Merging Two Lists into a Dictionary
-
Python Programming Tips – Zip Merging Lists into a Dictionary
-
Generating All Permutations
-
Basic Algorithms in Python Programming – Generating All Permutations
Here you can find programming, algorithms, large models, music (popular/indie), a little attention, and come here every day to learn and listen to music~