我正在尝试使用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]]
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]]