Python转到gen中的特定迭代

2024-04-24 20:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来导航到生成器对象中的特定迭代。你知道吗

我有一个生成器对象,它遍历JSON对象列表。我没有一次加载所有的JSON对象,而是创建了一个生成器,这样每个JSON对象只在每次迭代时加载。你知道吗

def read_data(file_name):
    with open(file_name) as data_file:
        for user in data_file:
            yield json.loads(user)

但是,现在我正在寻找某种方法来导航到第n次迭代,以检索有关该用户的更多数据。我能想到的唯一方法是遍历生成器并停止第n个枚举:

n = 3
data = read_data(file_name)
for num, user in enumerate(data):
    if num == n:
        <retrieve more data>

有更好的方法吗?你知道吗


Tags: 对象方法nameinjson列表forread
1条回答
网友
1楼 · 发布于 2024-04-24 20:29:15

这应该做到:

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)

这是许多useful utilities included in the ^{} documentation中的一个。你知道吗

相关问题 更多 >