预计阅读本页时间:-
Loop Coding Techniques
The for loop subsumes most counter-style loops. It’s generally simpler to code and quicker to run than a while, so it’s the first tool you should reach for whenever you need to step through a sequence. But there are also situations where you will need to iterate in more specialized ways. For example, what if you need to visit every second or third item in a list, or change the list along the way? How about traversing more than one sequence in parallel, in the same for loop?
You can always code such unique iterations with a while loop and manual indexing, but Python provides two built-ins that allow you to specialize the iteration in a for:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- The built-in range function produces a series of successively higher integers, which can be used as indexes in a for.
- The built-in zip function returns a series of parallel-item tuples, which can be used to traverse multiple sequences in a for.
Because for loops typically run quicker than while-based counter loops, it’s to your advantage to use tools like these that allow you to use for when possible. Let’s look at each of these built-ins in turn.