在Python或NumPy中,找出第一次出现的子阵列的最佳方法是什么?
例如,我有
a = [1, 2, 3, 4, 5, 6]
b = [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
找出b出现在哪里的最快方法(运行时间)是什么?我理解字符串这非常容易,但对于列表或numpy ndarray呢?
非常感谢!
[编辑]我更喜欢numpy解决方案,因为从我的经验来看,numpy矢量化比Python列表理解要快得多.同时,大数组是巨大的,所以我不想把它转换成字符串; 这将是(太长).
问题如下.我有一个字符串列表
lst1=['puffing','his','first','cigarette','in', 'weeks', 'in', 'weeks']
Run Code Online (Sandbox Code Playgroud)
我想获得这个字符串
lst2=['puffing','his','first','cigarette','in weeks', 'in weeks']
Run Code Online (Sandbox Code Playgroud)
这是为了连接子列表的任何出现['in', 'weeks'],原因与此处无关,find_sub_list1从这里取得(并包含在下面的代码中):
npis = [['in', 'weeks'], ['in', 'ages']]
# given a list a candidate sublist, return the index of the first and last
# element of the sublist within the list
def find_sub_list1(sl,l):
results=[]
sll=len(sl)
for ind in (i for i,e in enumerate(l) if e==sl[0]):
if l[ind:ind+sll]==sl:
results.append((ind,ind+sll-1))
return results
def concatenator(sent, npis):
indices = []
for npi in npis:
indices_temp = find_sub_list1(npi, sent) …Run Code Online (Sandbox Code Playgroud) 我试图通过使用开始和结束模式从Python2.7中提取一个更大的整数列表中的列表/子列表.我想用一个函数来做,但我找不到一个库,算法或正则表达式来解决这个问题.
def myFunctionForSublists(data, startSequence, endSequence):
# ... todo
data = [99, 99, 1, 2, 3, 99, 99, 99, 4, 5, 6, 99, 99, 1, 2, 3, 99, 4, 5, 6, 99]
startSequence = [1,2,3]
endSequence = [4,5,6]
sublists = myFunctionForSublists(data, startSequence, endSequence)
print sublists[0] # [1, 2, 3, 99, 99, 99, 4, 5, 6]
print sublists[1] # [1, 2, 3, 99, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以实现它吗?