Nic*_* M. 0 python for-loop list while-loop
我有一个生成两个列表的程序.我想从list1打印一个项目,然后切换到从列表2打印项目,然后从list1 ..etc返回打印.然而,每当我尝试它时,它只打印list1然后list2.
请帮忙.
码:
List1 = ['a', 'b' , 'c', 'd', 'e', 'f']
List2 = ['1', '2', '3', '4', '5', '6']
continue = True
while continue == True:
for i in List1:
print i
print '/n'
continue = False
while continue == False:
for i in List2:
print i
print '/n'
continue = True
Run Code Online (Sandbox Code Playgroud)
输出:
a
b
c
d
e
f
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
期望的输出:
a
1
b
2
c
3
d
4
e
5
f
6
Run Code Online (Sandbox Code Playgroud)
Python的内置zip功能提供了一种实现该目标的非常简洁的方法.
for x,y in zip(List1,List2):
print(x)
print(y)
# Out:
a
1
b
2
c
3
d
4
e
5
f
6
Run Code Online (Sandbox Code Playgroud)
这是一个更加Pythonic的解决方案.你不需要两个不同的循环,你需要一个循环按你想要的顺序打印它们."zip"函数将列表成对,然后随着循环的进行将每对放入x,y.因此,您将能够在列表的每次迭代中打印每个列表中的值.
有时在提问时,人们可能会遇到xy问题,他们在问题中询问他们对问题的解决方案,而不是询问问题本身.退后一步并询问您的方法是否是最好的方法总是好的,如果您遇到问题,可能还有哪些方法可行.看起来你正在考虑将你的问题作为在两个列表之间来回跳转的问题,这导致你想到两个循环,每个列表一个循环.但更好的解决方案是使用单个循环来同时跟踪两个列表.