Find all consecutive sub-sequences of length n in a sequence

前端 未结 4 1300
野的像风
野的像风 2020-12-10 18:03

I want to find all consecutive sub-sequences of length n in a sequence.

E.g. say n was 3 and the sequence was:

[0,1,7,3,4,5,10]

I w

4条回答
  •  余生分开走
    2020-12-10 18:43

    The following might probably be suit for you:

    def subseqs(xs, n):
      all_seqs = (xs[i:j+1] for i, _ in enumerate(xs) for j, _ in enumerate(xs))
      return filter(lambda seq: len(seq) == n, all_seqs)
    
    >>> xs = [1, 2, 3, 4, 5, 6] # can be also range(1, 7) or list(range(1, 7)) 
    >>> list(subseqs(xs, 3))
    [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
    

    Or simply, for getting all of the sequences of a list named 'xs':

    [xs[i:j+1] for i, _ in enumerate(xs) for j, _ in enumerate(xs)]
    

    For getting the sequences of a list named 'xs' that are only from length n:

    [xs[i:j+1] for i, _ in enumerate(xs) for j, _ in enumerate(xs) if len(xs[i:j+1]) == n]
    

提交回复
热议问题