Python:返回主列表中每个子列表出现的所有索引

时间:2016-06-10 23:17:37

标签: python list indexing indices sublist

我有一个主列表和一个子列表,我想找到主列表中每个出现的子列表的索引,在这个例子中,我想要返回以下索引列表。

>>> 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 个答案:

答案 0 :(得分: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)]

这个问题的唯一问题是它不计入重叠值

答案 1 :(得分: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 

答案 2 :(得分:-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