通过多个列表进行并行迭代,并在迭代项目上建立索引

问题描述

我正在尝试对多个来自不同列表的项目并行执行一个公式。

  1. 首先,我的列表如下:
    l1= [1,2,3]
    l2= [4,5,6]
    l3= [7,8,9]
  1. 接下来,我需要从主列表中创建一组新的列表,以便比较列表中的每对元素:
    newl1 = list(zip(l1,l1[1:])) #outputs [(1,2),(2,3)]
    newl2 = list(zip(l2,l2[1:])) #outputs [(4,5),(5,6)]
    newl3 = list(zip(l3,l3[1:])) #outputs [(7,8),(8,9)]
  1. 现在,我想并行遍历所有新的列表集,并能够比较元组列表元素:
    for pair_of_newl1,pair_of_newl2,pair_of_newl3 in newl1,newl2,newl3:
        if pair_of_newl1[0] > pair_of_newl1[1]:
            x = pair_of_newl1[0] + pair_of_newl2[1] + pair_of_newl3[1]
            print (x)
        elif pair_of_newl1[0] < pair_of_newl1[1]:
            x = pair_of_newl1[0] - pair_of_newl2[1] - pair_of_newl3[1]
            print (x)

在第一次迭代中期望它:

    pair_of_newl1 = (1,2)
    pair_of_newl2 = (4,5)
    pair_of_newl3 = (7,8)

因此可以通过索引比较其中的项目。

我遇到以下错误

ValueError: not enough values to unpack (expected 3,got 2)

我很困惑,删除了最后一个列表,只剩下两个列表可以使用:

l1= [1,3]
l2= [4,6]

newl1 = list(zip(l1,3)]
newl2 = list(zip(l2,6)]

for pair_of_newl1,pair_of_newl2 in newl1,newl2:
    if pair_of_newl1[0] > pair_of_newl1[1]:
        x = pair_of_newl1[0] + pair_of_newl2[1]
        print (x)
    elif pair_of_newl1[0] < pair_of_newl1[1]:
        x = pair_of_newl1[0] - pair_of_newl2[1]
        print (x)
    print (pair_of_newl1,pair_of_newl2) #just to see how the loop works

我得到:

-1
(1,2) (2,3)
-1
(4,5) (5,6)

因此,据我了解,pair_of_newl2被视为newl1的第二项,但为什么不选择newl2呢?

请帮助。

解决方法

您得到的错误是因为:for pair_of_newl1,pair_of_newl2,pair_of_newl3 in newl1,newl2,newl3行试图遍历三个列表,从每个列表中提取三个元素。但是,新列表仅包含两个元素。那是行不通的。

如果要遍历并行列表,可以压缩它们(这会使索引变复杂一些),或者可以使用索引迭代器:

     for i in range(len(newl1)): # For index 0 and 1,each of the list has
        if newl1[i][0] > newl1[i][1]:
            x = newl1[i][0] + newl2[i][1] + newl2[i][1]
            print(x)
        elif newl1[i][0] > newl1[i][1]:
            x = newl1[i][0] - newl2[i][1] - newl2[i][1]
            print (x)

这将循环遍历三个列表的两个元组,然后将第二个列表和第三个列表的第二个元素添加到第一个列表的第一个元素,或者将它们相减。

这是你想做的吗?

,

您忘记添加zip来进行迭代:

for pair_of_newl1,pair_of_newl2 in zip(newl1,newl2):

结果:

-4
(1,2) (4,5)
-4
(2,3) (5,6)