我有两个函数,每个函数都有 for 循环,我想要的只是 运行 函数一个一个地迭代一次
I've two functions both have for loop each, All I want is too run the function one by one with one iteration only
我的代码:-
def looping():
for i in range(1,4):
print('*')
def not_looping():
for j in range(1,4):
print('-')
looping()
not_looping()
我得到的输出:-
*
*
*
-
-
-
我想要的输出
*
-
*
-
*
-
我也访问过这个 post,并按照 post 应用我的逻辑,但它仍然为我提供相同的输出。
也许你想要发电机?
def a_gen():
for _ in range(4):
yield "*"
def b_gen():
for _ in range(4):
yield "-"
ag = a_gen()
bg = b_gen()
while (a := next(ag, None)) and (b := next(bg, None)):
print(a)
print(b)
注意:只要两个生成器中的一个耗尽,这个 while 循环就会终止。在这种情况下,两个生成器恰好产生相同数量的对象。
我的代码:-
def looping():
for i in range(1,4):
print('*')
def not_looping():
for j in range(1,4):
print('-')
looping()
not_looping()
我得到的输出:-
*
*
*
-
-
-
我想要的输出
*
-
*
-
*
-
我也访问过这个 post,并按照 post 应用我的逻辑,但它仍然为我提供相同的输出。
也许你想要发电机?
def a_gen():
for _ in range(4):
yield "*"
def b_gen():
for _ in range(4):
yield "-"
ag = a_gen()
bg = b_gen()
while (a := next(ag, None)) and (b := next(bg, None)):
print(a)
print(b)
注意:只要两个生成器中的一个耗尽,这个 while 循环就会终止。在这种情况下,两个生成器恰好产生相同数量的对象。