简体   繁体   中英

How to find all elements between two elements repeatedly in a list in Python?

I have a list that looks like

[item 1, abc, item 2, def, item 3, ghi, item 1, jkl, item 2]

I want to find all elements between 'item 1' and 'item 2', together with the start element 'item 1'.

What I want should look like:

[item 1, abc, item 1, jkl]

By the way, for 'item 1' and 'item 2', I prefer to use regular expression to match them, since it may varies in different texts, eg, 'item 1' in some texts, but 'item1' in other texts.

Is there any way to work it out? Thanks!

Next code finds leftmost match of regex re1 and rightmost of regex re2 and prints this sub-range, if any re1 not found then sub-range starts from 0-th element, if re2 not found the ends at the end of list.

If you need to throw error when re1 or re2 not found then replace [default] with [] in code.

Try it online!

import re
l = ['some 1', 'some', 'item 1', 'abc', 'item 2', 'def', 'item 3', 'ghi', 'item 1', 'jkl', 'item 2', 'item 3']
re1, re2 = r'item 1', r'item 2'
begin, end = [
    ([i for i, e in enumerate(l) if re.fullmatch(r, e)] or [default])[idx]
    for r, (default, idx) in ((re1, (0, 0)), (re2, (len(l), -1)))
]
print(l, '\n', begin, end, '\n', l[begin : end])

Output of code above:

['some 1', 'some', 'item 1', 'abc', 'item 2', 'def', 'item 3', 'ghi', 'item 1', 'jkl', 'item 2', 'item 3'] 
 2 10 
 ['item 1', 'abc', 'item 2', 'def', 'item 3', 'ghi', 'item 1', 'jkl']

Try this:

my_list = ['some 1', 'some', 'item 1', 'abc', 'item 2', 'def', 'item 3', 'ghi', 'item 1', 'jkl', 'item 2', 'item 3']
index_1 = [i for i, val in enumerate(my_list) if val == 'item 1']
index_2 = [i for i, val in enumerate(my_list) if val == 'item 2']
output = []
for i, j in zip(index_1, index_2):
    output.extend(my_list[i:j])
print(output)

Result:

['item 1', 'abc', 'item 1', 'jkl']

However it works only if item 2 is followed by item 1 . if that's not the case some care has to be taken before the last for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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