2016-06-10 116 views
0

我有一個主列表和一個子列表,我想找到在主列表中找到的每個子列表出現的索引,在這個例子中,我想要返回下面的索引列表。Python:返回主列表中每次出現子列表的所有索引

>>> main_list = [1,2,3,4,4,4,1,2,3,4,4,4] 
>>> sub_list = [4,4,4] 

>>> function(main_list, sub_list) 
>>> [3,9] 

理想情況下,函數也應該忽略sub_list的片段,在這種情況下[4,4]將被忽略。另外,我希望這些元素都是單個數字的整數。這是第二個例子,爲了清楚:

>>> main_list = [9,8,7,5,5,5,5,5,4,3,2,5,5,5,5,5,1,1,1,5,5,5,5,5] 
>>> sub_list = [5,5,5,5,5] 

>>> function(main_list, sub_list) 
>>> [3,11,19] 
+3

什麼用'main_list = [4發生, 4,4]'和'sub_list = [4,4]'? –

+0

你的用例總是用單個數字元素嗎?因爲那樣你可以製作一個簡單的基於正則表達式的解決方案。 – wim

+0

@MosesKoledoye我認爲這將返回[0,1] – iPhynx

回答

-1

您應該能夠使用一個for循環,但隨後其分解成你的長度SUB_LIST列表,遍歷,並尋找在子列表您主要清單。試試這個:

main_list = [9,8,7,5,5,5,5,5,4,3,2,5,5,5,5,5,1,1,1,5,5,5,5,5] 
sub_list = [5,5,5,5,5] 

indices = [] 
for i in range(0, len(main_list)-len(sub_list)+1): 
    temp_array = main_list[i:i+len(sub_list)] 
    if temp_array == sub_list: 
     indices.append(i) 

print indices 
0

也許使用字符串是要走的路嗎?

import re 
original = ''.join([str(x) for x in main_list]) 
matching = ''.join([str(x) for x in sub_list]) 
starts = [match.start() for match in re.finditer(re.escape(matching), original)] 

與這一個唯一的問題是,它不重疊值

+0

Padraic Cunningham在我認爲這個問題的評論中提供的答案好得多,它也考慮到了重疊的值。 – Aquiles

0

這裏有一個遞歸的方式做到這一點數:

list = [9,8,7,5,5,5,5,5,4,3,2,5,5,5,5,5,1,1,1,5,5,5,5,5] 

def seq(array): # get generator on the list 
    for i in range(0,len(array)): 
     yield i 

sq = seq(list) # get the index generator 



def find_consecutive_runs(array): # Let's use generator - we are not passing index 

    i=next(sq) # get the index from generator 

    if len(array) > 5: # or 3, or 4, or whatever - get slice and proceed 

     arr = array[:5] # slice 5 elements 

     if all(x==arr[0] for x in arr): # all list elements are identical 
      print i # we found the index - let's print it 

     find_consecutive_runs(array[1:len(array)]) # proceed with recursion 

find_consecutive_runs(list) # the actual call