I'm looking for a way to navigate to a particular iteration in a generator object.
I have a generator object that goes through a list of JSON objects. Instead of loading all of them at once, I created a generator so that each JSON object loads only at each iteration.
def read_data(file_name):
with open(file_name) as data_file:
for user in data_file:
yield json.loads(user)
However, now I am looking for some way to navigate to the nth iteration to retrieve more data on that user. The only way I can think of doing this is iterating through the generator and stopping on the nth enumeration:
n = 3
data = read_data(file_name)
for num, user in enumerate(data):
if num == n:
<retrieve more data>
Any better ways to do this?
This should do it:
from itertools import islice
def nth(iterable, n, default=None):
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)
This is one of many useful utilities included in the itertools documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With