我想知道是否可以避免嵌套的for循环,并使用itertools模块中的无限迭代器之一,例如cycle
或repeat
以获取预期的输出?
测试:
$ python3 test.py
Expected output:
A 0
B 0
C 0
A 100
B 100
C 100
A 200
B 200
C 200
A 300
B 300
C 300
A 400
B 400
C 400
A 500
B 500
C 500
Incorrect output:
A 0
B 100
C 200
A 300
B 400
C 500
A 600
test.py:
from itertools import count, cycle, repeat
STEP = 100
LIMIT = 500
TEAMS = ['A', 'B', 'C']
def test01():
for step in count(0, STEP):
for team in TEAMS:
print(team, step)
if step >= LIMIT: # Limit for testing
break
def test02():
for team, step in zip(cycle(TEAMS), count(0, STEP)):
print(team, step)
if step > LIMIT: # Limit for testing
break
def main():
print('Expected output:')
test01()
print('Incorrect output:')
test02()
if __name__ == "__main__":
main()
更新:2020年2月11日星期二10:17:17 UTC:
我最初没有提到这个,但是循环应该是无限的,因为step
的停止值是预先未知的。
itertools.product
正如文档所说,from itertools import product
for i, j in product(range(0, 501, 100), 'ABC'):
print(j, i)
等于product(A, B)
。
[tomjn的答案对于有限循环是最好的,因此,如果您不想使用((x,y) for x in A for y in B)
(对于无限循环),则可以使用此答案:
itertools.product
您可以按以下方式更改功能并获得所需的输出
def test01():
for step in range(0, LIMIT+1, STEP):
for team in TEAMS:
print(team, step)