简体   繁体   English

遍历Python列表中的对并在迭代过程中更新对

[英]Iterate through pairs in a Python list and update the pairs during the iteration

Hi I am trying to make a code that iterates over pair in a list and updates the pair if condition fulfil 嗨,我正在尝试编写一个代码,以遍历列表中的对并在条件满足时更新对

List=[A1,A2,A4,A5,E3,A3,E1,A7,E2,E3]

This is what I have so far: 这是我到目前为止的内容:

def pairwise(ListX):
"Pairs -> (A1,A2), (A2,A4), (A4, A5),(A5, E3),(E3, A3),(A3, E1), ..."
a, b = tee(ListX)
next(b, None)
return izip(a, b)

for a, b in pairwise(List):
  if a!= b and a == 'E':
   do something and switch positions

In this case, the pair (E3, A3) will be switched and the new order will be ( A3,E3) and then the new pair to iterate will be will be: (E3, E1) and not (A3, E1). 在这种情况下,将切换对(E3,A3),新的订单将是(A3,E3),然后要迭代的新对将是(E3,E1),而不是(A3,E1)。 The code I have so far make the action and switch the order of the list: 到目前为止,我拥有的代码可以执行操作并切换列表的顺序:

    List=[A1,A2,A4,A5,E3,A3,E1,A7,E2,E3] <--Initial
    List=[A1,A2,A4,A5,A3,E3,E1,A7,E2,E3]  <--Switched

However after the switch keep iterating on the pair (A3, E1). 但是,在开关之后,请继续在线对(A3,E1)上进行迭代。

Any suggestions? 有什么建议么?

I think there is no reason to use pairwise function because it's return new object. 我认为没有理由使用成对函数,因为它返回了新对象。

l = ['A1', 'A2', 'A4', 'A5', 'E3', 'A3', 'E1', 'A7', 'E2', 'E3']
for i in range(len(l)-1):
    if l[i] != l[i+1] and l[i][:1] == 'E':
        l[i], l[i+1] = l[i+1], l[i]
        break
print(l)

If you remove break next pair be ('E3', 'E1') 如果删除下一个break对,则为('E3','E1')

Your code doesn't work because of how itertools.tee is implemented. 由于实现itertools.tee方式,您的代码无法正常工作。 Because it works on arbitrary iterators (not only sequences), it needs to store the values yielded by one of the iterators but not by the other. 因为它适用于任意迭代器(不仅是序列),所以需要存储其中一个迭代器而不是另一个迭代器产生的值。

You can work around this though, since you're actually calling your pairwise function on a list, which you can independently iterate over multiple times. 但是,您可以解决此问题,因为实际上是在列表上调用pairwise函数,您可以独立地迭代多次。

def pairwise(ListX):
    a = iter(ListX)
    b = iter(ListX)
    next(b, None)
    return izip(a, b)

Now, if you modify ListX while iterating over the pairs, the updates will always be seen. 现在,如果在迭代对时修改ListX ,将始终看到更新。

Note that to do your modifications efficiently, you might want to use enumerate to get an index along with the pair values. 请注意,为了有效地进行修改,您可能需要使用enumerate来获取索引和对值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM