Python 如何在中间迭代一个列表并开始倒退?

Python 如何在中间迭代一个列表并开始倒退?,python,Python,如果在事件列表中进行迭代,如何在特定条件下停止并开始在列表中反向迭代。e、 g for p in pattern: for event in p: if event == 1: # Iterate backwards through p from current position until you reach the last event that equals 1 我想您可以使用类似于reversed(p),但这将从p的末尾开始,我想从当前位置开始查

如果在事件列表中进行迭代,如何在特定条件下停止并开始在列表中反向迭代。e、 g

for p in pattern:
    for event in p:
        if event == 1:
        # Iterate backwards through p from current position until you reach the last event that equals 1

我想您可以使用类似于
reversed(p)
,但这将从
p
的末尾开始,我想从当前位置开始查看

Python for循环的工作方式与我认为的不同。当您在这里调用
for
时,Python实际上是在将
p[i]
赋值给变量
事件的新副本。它没有要引用的下一个对象或上一个对象

如果您想知道当前的职位,需要使用
enumerate()
函数

对于索引,枚举中的事件(p):
打印(索引、事件)
这将允许您中断循环或创建另一个子循环,然后使用
reversed()
或类似的方法从指定点重新横切它

您的代码看起来像:

模式中的p的
:
对于索引,枚举中的事件(p):
如果事件==1:
对于反向(p[:索引])中的事件2:
#做事
我假设你不需要列举你的反转。如果这样做,将最里面的
for
语句更改为
for in enumerate(反向(p[:index]):
应该可以做到这一点

我使用了一个不同的事件变量,以防您想要引用最初发送给您反转的事件变量。如果您不需要该功能,则不必这样做

选项2:

另一种方法(谢谢)是使用
p.index(event)
值。它不太像pythonic,会打破你现有的循环(也许这很重要,也许不是),但它确实有效

模式中的p的
:
对于p中的事件:
如果事件==1:
新开始=p.index(事件)
对于反向中的p(p[:新开始]):

要反转方向,您需要在迭代时记住位置索引。内置函数会有所帮助

一旦发现反转条件,就用它来隔离你想反向重复的部分。内置程序将从那里获取它

>>> loe = ['e0', 'e1', 'e2', 'e3', 'e4', 'e5']
>>> for i, event in enumerate(loe):
        print event
        if event == 'e3':
            for event in reversed(loe[:i]):
                print event
            break


e0
e1
e2
e3
e2
e1
e0

希望这有帮助:-)

只需记录索引并开始向后遍历: 应该是这样的

pattern = [[3,4,5],[7,8,9],[3,2,1,5,7,1],[8,1,8,8,1]]

for i in range(0, len(pattern)):
  for j in range(0, len(pattern[i])):
    print(pattern[i][j])
    if(pattern[i][j] == 1):
      print("found a event equals to 1")
      if(j == 0):
        print(" but its at the start of the list so there are no event equals to 1 before")
      else:
        reserveStartingIndex = j - 1 #to exclude itself 
        for r in range (reserveStartingIndex, 0, -1):
          if(pattern[i][r] == 1):
            print("found a event equals to 1 before at the index of: " + repr(r) )
          elif(r == 0):
            print("no event equals to 1 before")
您将得到如下结果:

3
4
5
7
8
9
3
2
1
found a event equals to 1
5
7
1
found a event equals to 1
found a event equals to 1 before at the index of: 2
8
1
found a event equals to 1
8
8
1
found a event equals to 1
found a event equals to 1 before at the index of: 1

由于您是从p开始迭代的,因此找到的第一个值
1
也必须是列表中最早的值。因此,向后迭代以找到一个更早的似乎没有多大意义,因为不可能有一个。你的算法还有更多吗?这个列表中有很多1,而且没有顺序。