【问题标题】:Python multi-lists iterationPython 多列表迭代
【发布时间】:2012-05-12 05:05:40
【问题描述】:

是否有一种巧妙的方法可以在 Python 中迭代 两个 列表(不使用 列表推导)?

我的意思是,像这样:

# (a, b) is the cartesian product between the two lists' elements
for a, b in list1, list2:
   foo(a, b)

代替:

for a in list1:
    for b in list2:
        foo(a, b)

【问题讨论】:

    标签: python list iteration


    【解决方案1】:

    itertools.product() 正是这样做的:

    for a, b in itertools.product(list1, list2):
      foo(a, b)
    

    它可以处理任意数量的迭代,在这个意义上比嵌套的for 循环更通用。

    【讨论】:

      【解决方案2】:
      for a,b in zip(list1, list2):
          foo(a,b)
      

      zip 将列表/数组的元素按元素组合成元组。例如

      list1 = [1,2,5]
      list2 = [-2,8,0]
      for i in zip(list1,list2):
          print(i)
      >>> (1, -2)
      >>> (2, 8)
      >>> (5, 0)
      

      【讨论】:

        【解决方案3】:

        使用 zip 它允许您压缩两个或多个列表并一次迭代。

        list= [1, 2]
        list2=[3,4]
        combined_list = zip(list, list2)
        for a in combined_list:
                print(a)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-05
          • 1970-01-01
          • 1970-01-01
          • 2019-05-05
          • 2013-10-07
          • 1970-01-01
          相关资源
          最近更新 更多