简体   繁体   English

如何在Python的列表中重复查找两个元素之间的所有元素?

[英]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'.我想找到“item 1”和“item 2”之间的所有元素,以及开始元素“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.顺便说一句,对于'item 1'和'item 2',我更喜欢使用正则表达式来匹配它们,因为它在不同的文本中可能会有所不同,例如,某些文本中的'item 1',而其他文本中的'item1' .

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.下一个代码查找正则表达式re1最左边匹配项和正则表达式re2最右边匹配项并打印此子范围,如果未找到任何re1则子范围从第 0 个元素开始,如果未找到re2 ,则在列表末尾处结束。

If you need to throw error when re1 or re2 not found then replace [default] with [] in code.如果在找不到re1re2时需要抛出错误,请在代码中将[default]替换为[]

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 .但是,它仅在item 2后跟item 1时才有效。 if that's not the case some care has to be taken before the last for loop如果情况并非如此,则在最后一个for循环之前必须小心

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

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