简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM