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

时间:2019-02-28 20:07:26

标签: python arrays list between

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

我需要能够处理诸如l = ['.','b','w','w','w','w','.','.']之类的情况,其中没有第二个'b',在这种情况下将不会返回任何内容。 l = ['.','b','w','w','.','.','b','.']可能会遇到其他情况,在这种情况下也不会返回任何内容。我需要能够获得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)

但是,这不能处理所有情况,有时会返回错误。我该怎么做没有numpy

2 个答案:

答案 0 :(得分:0)

尝试

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)

答案 1 :(得分:0)

尝试一下:

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)