【发布时间】:2015-12-07 07:56:15
【问题描述】:
是否可以在同一个循环中遍历多个列表并从不同列表返回参数?
即,而不是 -
For x in trees:
Print(x)
For y in bushes:
Print(y)
有点像 -
For x,y in trees,bushes:
Print(x +"\n"+ y)
【问题讨论】:
标签: python list loops for-loop
是否可以在同一个循环中遍历多个列表并从不同列表返回参数?
即,而不是 -
For x in trees:
Print(x)
For y in bushes:
Print(y)
有点像 -
For x,y in trees,bushes:
Print(x +"\n"+ y)
【问题讨论】:
标签: python list loops for-loop
您可以简单地使用zip 或itertools.izip:
for x, y in zip(trees, bushes):
print x, y
【讨论】:
future_builtins.zip,这对于编写适用于 python2.x 和 3.x 的代码非常方便(只需使用 try: ... except ImportError: pass 套件保护 import 语句)。
你可以使用zip():
a=['1','2','2']
b=['3','4','5']
for x,y in zip(a,b):
print(x,y)
输出:
1 3
2 4
2 5
【讨论】: