Python—在每次迭代中同时迭代两个列表,而不移动到这两个列表中的下一行

Python—在每次迭代中同时迭代两个列表,而不移动到这两个列表中的下一行,python,list,iteration,Python,List,Iteration,我已经查找了很多,找到了itertools包,但据我所知,没有一个函数能完全满足我的需要。我已经开始自己编写一个函数,我可以这样做,但我想知道是否有人知道一个内置函数可以完成这个双重列表迭代的全部或部分 我想做的是一次迭代两个列表,比较其中每个列表的值,作为比较的结果做一些事情,并且可能在移动到第二个列表的下一行时停留在一个列表的同一行上(根据比较结果)。下面是一个例子: ListA= [[1, 7, 3], [1, 12, 4], [1, 9, 5]] Lis

我已经查找了很多,找到了itertools包,但据我所知,没有一个函数能完全满足我的需要。我已经开始自己编写一个函数,我可以这样做,但我想知道是否有人知道一个内置函数可以完成这个双重列表迭代的全部或部分

我想做的是一次迭代两个列表,比较其中每个列表的值,作为比较的结果做一些事情,并且可能在移动到第二个列表的下一行时停留在一个列表的同一行上(根据比较结果)。下面是一个例子:

ListA= [[1, 7, 3],
        [1, 12, 4],
        [1, 9, 5]]

ListB= [[2, 2, 3],
        [2, 2, 3],
        [2, 5, 4]]
我想逐行检查每个列表,并比较最后位置的数字。如果它们相等,我想把这两个数相加。但是我想继续添加它们,只要ListB中的第三个数字等于ListA中的第三个数字。这意味着ListA可能会保持在同一行,而ListB会向下移动几行(这就是为什么itertools函数不起作用,因为它们似乎都是串联在一起的,将每个列表的每一行分块)。因此,我希望输出如下所示:

Iteration 1 ListOut= [[9, 3]]

Iteration 2 ListOut= [[11,3]]

Iteration 3 ListOut= [[11,3], [17, 4]]

Iteration 4 ListOut= [[11,3], [17, 4],  [9, 5]]
listb_iter = iter(ListB)
item_b = next(listb_iter) #we're assuming that ListB as at least one item.
for item_a in ListA:
    if ...: #condition to move on to the next item in ListB
        try:
            item_b = next(listb_iter)
        except StopIteration:
            #went through all of ListB

    #other logic

您可能希望执行以下操作:

Iteration 1 ListOut= [[9, 3]]

Iteration 2 ListOut= [[11,3]]

Iteration 3 ListOut= [[11,3], [17, 4]]

Iteration 4 ListOut= [[11,3], [17, 4],  [9, 5]]
listb_iter = iter(ListB)
item_b = next(listb_iter) #we're assuming that ListB as at least one item.
for item_a in ListA:
    if ...: #condition to move on to the next item in ListB
        try:
            item_b = next(listb_iter)
        except StopIteration:
            #went through all of ListB

    #other logic

您可能希望执行以下操作:

Iteration 1 ListOut= [[9, 3]]

Iteration 2 ListOut= [[11,3]]

Iteration 3 ListOut= [[11,3], [17, 4]]

Iteration 4 ListOut= [[11,3], [17, 4],  [9, 5]]
listb_iter = iter(ListB)
item_b = next(listb_iter) #we're assuming that ListB as at least one item.
for item_a in ListA:
    if ...: #condition to move on to the next item in ListB
        try:
            item_b = next(listb_iter)
        except StopIteration:
            #went through all of ListB

    #other logic

你所要求的是如此具体,以至于任何普通图书馆都不可能拥有它。所以列表总是按照第三项排序?是的,两个列表都按照第三项排序!你所要求的是如此具体,以至于任何普通图书馆都不可能拥有它。所以列表总是按照第三项排序?是的,两个列表都按照第三项排序!