如何获取列表中两个相同元素之间的连续元素?

How do I get the consecutive elements between two identical elements in a list?

例如我有一个列表l = ['.','b','w','w','w','b','.','.'],我将如何遍历这个列表和return b 之间的三个w 的索引。

我需要能够处理诸如 l = ['.','b','w','w','w','w','.','.'] 之类的情况,其中没有第二个 'b',在这种情况下不会 returned。其他可能遇到的情况是 l = ['.','b','w','w','.','.','b','.'],在这种情况下也不会 returned。我需要能够在 b 之间获得连续的 w。到目前为止我尝试过的是:

l = ['.','b','w','w','.','.','.','.']
q = []
loop = False
for i in range(len(l)):
    if l[i] == 'b' and l[i+1] == 'w':
        loop = True
    elif l[i] == 'w' and l[i+1] == 'w' and l[i+2] == '.':
        pass
    elif l[i] == 'w' and l[i-1] == 'b' and l[i+1] == 'w' and loop == True:
        q.append(i)
    elif l[i-1] == 'w' and l[i] == 'w' and l[i+1] == 'w' and loop == True:               q.append(i)
    elif l[i] == 'w' and l[i+1] == 'b' and loop == True:
        q.append(i)
        loop = False
        break

print(q)

但这并不能处理所有情况,有时还会出现 returns 错误。如果没有 numpy,我怎么能做到这一点

试试这个

import re
l = ['.','b','w','w','b','.','.','.']
s = ''.join(l)

# print(re.findall('[b]([w]+)[b]',s))
# print(re.findall('[w]([b]+)[w]',s))

if(re.findall('[b]([w]+)[b]',s)):
    witer =re.finditer('w',s)
    wpos = []
    for i in witer:
        wpos.append(i.start())
    print('reverse', wpos)


if(re.findall('[w]([b]+)[w]',s)):
    biter =re.finditer('b',s)
    bpos = []
    for i in biter:
        bpos.append(i.start())
    print('reverse', bpos)

试试这个:

ind = [i for i, e in enumerate(l) if e == 'b']
q = []

if len(ind) == 2:
    w = l[ind[0]+1: ind[1]]
    if set(w) == {'w'}:
        for i in range(ind[0]+1, ind[1]):        
            q.append(i)