使用yield将列表函数转换为生成器

问题描述 投票:0回答:1

我正在尝试使用yield 将 for 循环转换为迭代器,但我的尝试失败了。我不明白为什么

yield
没有给我预期的输出。有谁知道问题出在哪里吗?

尝试使用yield:

def iteration_order(dimensions):
    for dim in range(dimensions):
        order = [0, dim, 0]
        yield order
        for j in range(6):
            sgn = 1 if j % 2 == 0 else -1
            idx = j % 3
            for _ in range(dim if j < 5 else dim-1):
                order[idx] += sgn
                yield order
print(list(iteration_order(2))
>>> [[0, 0, 0], [0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1], [0, 1, 1]]

代码应该可以工作(不使用yield时):

def iteration_order(dimensions):
    full_order = []
    for dim in range(dimensions):
        order = [[0, dim, 0]]
        for j in range(6):
            sgn = 1 if j % 2 == 0 else -1
            idx = j % 3
            for _ in range(dim if j < 5 else dim-1):
                nxt = list(order[-1])
                nxt[idx] += sgn
                order.append(nxt)

        full_order.extend(order)
    return full_order
print(iteration_order(2))
>>> [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1], [0, 1, 1]]
python python-3.x yield
1个回答
1
投票

IIUC,你可以这样做:

def iteration_order(dimensions):
    for dim in range(dimensions):
        order = [[0, dim, 0]]
        for j in range(6):
            sgn = 1 if j % 2 == 0 else -1
            idx = j % 3
            for _ in range(dim if j < 5 else dim - 1):
                nxt = list(order[-1])
                nxt[idx] += sgn
                order.append(nxt)
        yield from order  # <-- yield from


print(list(iteration_order(2)))

打印:

[[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1], [0, 1, 1]]
© www.soinside.com 2019 - 2024. All rights reserved.