gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:06 25 4
gpt4 key购买 nike

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

基本上,一旦找到特定的数字序列,我就需要拆分列表,类似于执行 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 启发的列表理解发布

关于如果找到数字序列,Python 拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32631062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com