Skip to main content
 首页 » 编程设计

如果找到数字序列,Python 拆分列表

2025年05月04日12飞鱼

我一直在尝试寻找相关问题,但我似乎无法搜索到正确的词,而且我所找到的只是如何检查列表是否包含交集。

基本上,一旦找到特定的数字序列,我就需要拆分列表,类似于执行 str.split(sequence)[0],但使用列表代替。我有工作代码,尽管它看起来不是很有效(也不知道引发错误是否是正确的解决方法),而且我确信必须有更好的方法来做到这一点。

郑重声明,long_list 可能有几百万个值的长度,这就是为什么我认为遍历它们可能不是最好的主意。

long_list = [2,6,4,2,7,98,32,5,15,4,2,6,43,23,95,10,31,5,1,73] 
end_marker = [6,43,23,95] 
end_marker_len = len(end_marker) 
 
class SuccessfulTruncate(Exception): 
    pass 
try: 
    counter = 0 
    for i in range(len(long_list)): 
        if long_list[i] == end_marker[counter]: 
            counter += 1 
        else: 
            counter = 0 
        if counter == end_marker_len: 
            raise SuccessfulTruncate() 
except SuccessfulTruncate: 
    long_list = long_list[:2 + i - end_marker_len] 
else: 
    raise IndexError('sequence not found') 
 
>>> long_list 
[2,6,4,2,7,98,32,5,15,4,2] 

好的,用 100 万个值的大列表来计时一些答案(标记非常接近尾声):

Tim: 3.55 seconds 
Mine: 2.7 seconds 
Dan: 0.55 seconds 
Andrey: 0.28 seconds 
Kasramvd: still executing :P 

请您参考如下方法:

I have working code, though it doesn't seem very efficient (also no idea if raising an error was the right way to go about it), and I'm sure there must be a better way to do it.

我在评论中评论了异常引发

Instead of raising an exception and catching it in the same try/except you can just omit the try/except and do if counter == end_marker_len: long_list = long_list[:2 + i - end_marker_len]. Successful is not a word thats fitting for an exception name. Exceptions are used to indicate that something failed

无论如何,这是一个更短的方法:

>>> long_list = [2,6,4,2,7,98,32,5,15,4,2,6,43,23,95,10,31,5,1,73] 
>>> end_marker = [6,43,23,95] 
>>> index = [i for i in range(len(long_list)) if long_list[i:i+len(end_marker)] == end_marker][0] 
>>> long_list[:index] 
[2, 6, 4, 2, 7, 98, 32, 5, 15, 4, 2] 

受 this 启发的列表理解发布