在python列表中向后或向前循环以查找匹配项

时间:2019-02-25 06:45:42

标签: python python-3.x python-2.7 jupyter-notebook spyder

我有一个python列表,我将在其中搜索并找到一个术语。找到它之后,我需要在列表中向后移动,并使用=找到第一个匹配项,然后向前移动并使用;找到第一个匹配项。

我尝试使用while循环,但无法正常工作。

extract = [1,2,"3=","fd","dfdf","keyword","ssd","sdsd",";","dds"]

indices = [i for i,s in enumerate(extract) if 'keyword' in s] 


for ind in indices:
    ind_while_for = ind
    ind_while_back = ind
    if ('=' in extract[ind]) & (';' in extract[ind]):
        print(extract[ind])   
    if (';' in extract[ind]) & ('=' not in extract[ind]):
        while '=' in extract[ind_while_back-1]:
            ind_while_back -= 1    
        print(' '.join(extract[ind_while_back:ind]))

需要的结果:3= fd dfdf keyword ssd sdsd ;

3 个答案:

答案 0 :(得分:1)

找到关键字的位置:

kw = extract.index("keyword")

在原始列表的子列表中的关键字位置之前找到索引最大的元素,该元素包含"="

eq = max(i for i,w in enumerate(extract[:kw]) 
         if isinstance(w,str) and "=" in w)

在从上一个元素到最后一个元素的子列表中找到索引中包含";"的索引最小的元素:

semi = min(i for i,w in enumerate(extract[eq:], eq) 
           if isinstance(w,str) and ';' in w)

在两个极端之间提取子列表:

extract[eq:semi+1]
#['3=', 'fd', 'dfdf', 'keyword', 'ssd', 'sdsd', ';']

答案 1 :(得分:1)

您可以使用:

l = [1, 2, "3=", "fd", "dfdf", "keyword", "ssd", "sdsd", ";", "dds"]

s = "keyword"

def take(last, iterable):
    l = []
    for x in iterable:
        l.append(x)
        if last in x:
            break
    return l

# get all elements on the right of s
right = take(';', l[l.index(s) + 1:])

# get all elements on the left of s using a reversed sublist
left = take('=', l[l.index(s)::-1])

# reverse the left list back and join it to the right list
subl = left[::-1] + right

print(subl)
['3=', 'fd', 'dfdf', 'keyword', 'ssd', 'sdsd', ';']

答案 2 :(得分:0)

尝试以下功能:

extract = ['1','2','3=','fd','dfdf','keyword','ssd','sdsd',';','dds']

def get_output_list(extract, key): 
    equals_indices = [i for i,j in enumerate(extract) if '=' in j]
    semicolon_indices = [i for i,j in enumerate(extract) if ';' in j]
    if key not in extract or len(equals_indices) == 0 or len(semicolon_indices) == 0: 
        return 'no match found1'
    keyword_index = extract.index(key) 
    if any([keyword_index<i for i in semicolon_indices]) and any([keyword_index>i for i in equals_indices]) : 
        required_equal_index = keyword_index - equals_indices[0]
        required_semicolon_index = semicolon_indices[0] - keyword_index
        for i in equals_indices: 
            if (i < keyword_index) and required_equal_index > i: 
                required_equal_index = i
        for i in semicolon_indices: 
            if (i > keyword_index) and (required_semicolon_index < i) :
                required_semicolon_index = i
        return extract[required_equal_index:required_semicolon_index+1]
    else : 
        return 'no match found'