Python基础课程:用Generator实现自定义enumerate函数的技术咨询
start Parameter & Building Your Generator Hey there! Let's unpack this problem so you can work through it independently.
First: Why start=0?
The start=0 is a default parameter here to match the behavior of Python's built-in enumerate() function, which starts counting from 0 by default. When you call my_enumerate(lessons, 1), you're overriding that default to start counting at 1—perfect for your "Lesson 1, Lesson 2..." output.
Generator Implementation Tips (No Spoilers!)
Here's a step-by-step thought process to build your generator:
- Track your counter: Initialize a variable to hold the current number you want to yield. This should start at the
startvalue passed into the function. - Loop through the iterable: Iterate over each item in the input
iterable(yourlessonslist, in this case). - Yield the pair: For each item, yield a tuple containing the current counter value and the item itself.
- Increment the counter: After yielding, make sure to increase your counter by 1 so the next item gets the correct number.
Remember, generator functions use the yield keyword instead of return—each time yield runs, it pauses the function and sends the value back, resuming where it left off on the next iteration.
If you get stuck, think about how you'd manually pair each lesson with its number without enumerate—the generator is just automating that process one step at a time!
内容的提问来源于stack exchange,提问作者Pepert

