繁体   English   中英

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

[英]looping backward or forward in python list to find a match

我有一个 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 ;

查找关键字的位置:

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', ';']

您可以使用:

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', ';']

尝试以下功能:

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'

暂无
暂无

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

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