【问题标题】:Iterate through multiple lists at the same time [duplicate]同时遍历多个列表[重复]
【发布时间】: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


【解决方案1】:

您可以简单地使用zipitertools.izip

for x, y in zip(trees, bushes):
  print x, y

【讨论】:

  • python2.x 也有 future_builtins.zip,这对于编写适用于 python2.x 和 3.x 的代码非常方便(只需使用 try: ... except ImportError: pass 套件保护 import 语句)。
  • @mgilson 好点。 Python 2.x,其中 x >= 6。
  • 哦,python 是否存在于更早的版本中 ;-)。我好像不记得了……
  • @mgilson 我仍然遇到比 2.6 更早版本的系统。很痛苦。
【解决方案2】:

你可以使用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

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 2012-05-26
    • 2021-11-29
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多