我想循环像:
for j in range(1,4) and for k in ['one', 'two', 'three']:
print(str(j) + ' is written ' + k)
Run Code Online (Sandbox Code Playgroud)
我试过and但它没有用.有人如何得到这种效果?
如果两个列表的长度不同,会发生什么?我怎么还能遍历它们呢?
您可以使用 zip
for j, k in zip(range(1,4), ['one', 'two', 'three']):
print('{} is written {}'.format(j, k))
1 is written one
2 is written two
3 is written three
Run Code Online (Sandbox Code Playgroud)
如果一个比另一个长,你可以考虑使用 itertools.zip_longest
看一下这个:
for j,k in enumerate(['one', 'two', 'three'], 1):
print("{} is written {}".format(j, k))
Run Code Online (Sandbox Code Playgroud)