gpt4 book ai didi

python - 让索引返回for循环

转载 作者:行者123 更新时间:2023-11-30 22:58:11 26 4
gpt4 key购买 nike

我试图用Python制作一个brainf**k解释器,并想出了如何进行循环的想法,因为我遇到了问题,但现在我需要让索引返回这样的 for 循环:

    for i in range(20):
if i == 15:
# Set i to 5
print(i)

但我不需要用 5 替换 15,而是返回索引:实际结果:

    1
2
3
4
5
6
7
8
9
10
11
12
13
14
5
16
17
18
19

预期结果:

    1
2
3
4
5
6
7
8
9
10
11
12
13
14
5
6
7
8
9

我怎样才能做到这一点,以便我可以返回 or 循环?

最佳答案

简单的for…循环是不可能的。

它可以通过 while 循环和计数器来执行:

i = 0
while i < 20:
i += 1

if i == 15:
i = 5
print(i)

另一种解决方案是使用协程:

def co_counter():
i = 0
new_i = None
while i < 20:
if new_i is not None:
i = new_i - 1
new_i = yield i
i += 1

counter = co_counter()
for i in counter:
if i == 15:
counter.send(5)
print(i)

关于python - 让索引返回for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36289094/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com