Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python go to specific iteration in generator

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?

like image 220
Aaron Yan Avatar asked Aug 12 '26 00:08

Aaron Yan


1 Answers

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.

like image 73
Cyphase Avatar answered Aug 13 '26 14:08

Cyphase