【问题标题】:Parallel iteration through multiple lists with indexing on the iterated item通过多个列表并行迭代,并在迭代项上建立索引
【发布时间】:2020-08-19 07:07:08
【问题描述】:

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

  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,2,3]
l2= [4,5,6]

newl1 = list(zip(l1, l1[1:])) #outputs [(1,2), (2,3)]
newl2 = list(zip(l2, l2[1:])) #outputs [(4,5), (5,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 呢?

请帮忙。

【问题讨论】:

  • 考虑到在这种情况下只满足第二个条件,我希望 x = 1 - 5

标签: python python-3.x iteration


【解决方案1】:

您忘记添加 zip 来迭代它们:

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

结果:

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

【讨论】:

    【解决方案2】:

    您得到的错误是因为行:for pair_of_newl1, pair_of_newl2, pair_of_newl3 in newl1, newl2, newl3 尝试遍历三个列表,从每个列表中提取三个元素。但是 newl-lists 每个只有两个元素。那是行不通的。

    如果您想遍历并行列表,您可以压缩它们(这会使索引在您的情况下更加复杂),或者您可以使用索引迭代器:

         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)
    

    这将遍历三个列表的两个元组,并将第二个和第三个列表的第二个元素添加到第一个列表的第一个元素或减去它们。

    这是你想做的吗?

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 2020-05-21
      • 2014-03-21
      • 2016-07-13
      • 1970-01-01
      • 2018-07-19
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多